returning index of minimum in a list of lists

JJLaRocque at gmail.com JJLaRocque at gmail.com
Wed Jun 21 12:04:11 EDT 2006


Thanks so much for your help.  I was wondering if there was anything
even simpler, but this will be great.

forman.simon at gmail.com wrote:
> JJLaRocque at gmail.com 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
>
> One way to do this is to generate (value, index-in-main-list,
> index-in-secondary-list) tuples and then just take the minimum.
>
> def f(L):
>     '''Return indices of the first minimum value in a list of lists.'''
>     return min(
>         (n, i, j)
>         for i, L2 in enumerate(L)
>         for j, n in enumerate(L2)
>         )[1:]
>
> L = [[3, 3, 3, 3], [3, 3, 3, 1], [3, 3, 3, 3]]
>
> print f(L) # prints (1, 3)
>
> Note: In python (and most other languages) indices begin at 0, so your
> return values of (2, 4) wouldn't be correct.
>
> For a list of numbers it's simpler.
>
> L = [3, 3, 3, 1, 3, 3]
> print min((n, i) for i, n in enumerate(L))[1] # prints 3
> 
> Hope this helps
> 
> ~Simon




More information about the Python-list mailing list