Velocity Reviews > returning index of minimum in a list of lists

# returning index of minimum in a list of lists

bearophileHUGS@lycos.com
Guest
Posts: n/a

 06-21-2006
This way is probably slowe (two scans of the list for l1, and even more
work for l2), but for small lists it's probably simple enough to be
considered:

For a simple list:
>>> l1 = [5, 3, 2, 1, 4]
>>> l1.index(min(l1))

3

For a list of lists:
>>> l2 = [[3, 3, 3, 3], [6], [10], [3, 3, 3, 1, 4], [3, 0, 3, 3]]
>>> mins = map(min, l2)
>>> mins

[3, 6, 10, 1, 0]
>>> pos1 = mins.index(min(mins))
>>> pos1

4
>>> subl = l2[pos1]
>>> subl.index(min(subl))

1

This solution is also fragile:
>>> l3 = [[3], []]
>>> mins = map(min, l3)

Traceback (most recent call last):
File "<interactive input>", line 1, in ?
ValueError: min() arg is an empty sequence

Bye,
bearophile

jantod@gmail.com
Guest
Posts: n/a

 06-22-2006
http://www.velocityreviews.com/forums/(E-Mail Removed) wrote:
> Hi all,
> Is there a simple python function to return the list index of the
> minimum entry in a list of lists?
> ie, for [[3,3,3,3], [3,3,3,1], [3,3,3,3]] to return 2,4.
> Or, same question but just for a list of numbers, not a list of lists.
> Thanks,
> Josh

Untested:

items = []
for x, a in enumerate(L):
for y, b in enumerate(a):
items.append((b, (x,y)))
x, y = min(items)[1]

You could also change this to a generator:

def f(L):
for x, a in enumerate(L):
for y, b in ebumerate(a):
yield b, (x,y)

x, y = min(f(L))[1]