returning index of minimum in a list of lists
bearophileHUGS at lycos.com
bearophileHUGS at lycos.com
Wed Jun 21 19:17:44 EDT 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
More information about the Python-list
mailing list