returning index of minimum in a list of lists

Steven Bethard steven.bethard at gmail.com
Wed Jun 21 12:11:33 EDT 2006


JJLaRocque at gmail.com wrote:
> 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.

In Python 2.5:

Python 2.5a2 (trunk:46491M, May 27 2006, 14:43:55) [MSC v.1310 32 bit 
(Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
 >>> x = [4, 4, 4, 1]
 >>> min(xrange(len(x)), key=x.__getitem__)
3
 >>> y = [[3,3,3,3], [3,3,3,1], [3,3,3,3]]
 >>> min(xrange(len(y)), key=[min(z) for z in y].__getitem__)
1
 >>> def multimin(listoflists):
...     mins = []
...     min_indices = []
...     for sublist in listoflists:
...         min_index = min(xrange(len(sublist)),
...                         key=sublist.__getitem__)
...         min_indices.append(min_index)
...         mins.append(sublist[min_index])
...     min_index = min(xrange(len(listoflists)), key=mins.__getitem__)
...     return min_index, min_indices[min_index]
...
 >>> multimin([[3,3,3,3], [3,3,3,1], [3,3,3,3]])
(1, 3)

STeVe



More information about the Python-list mailing list