returning index of minimum in a list of lists

Paul McGuire ptmcg at austin.rr._bogus_.com
Wed Jun 21 11:58:54 EDT 2006


"Maric Michaud" <maric at aristote.info> wrote in message
news:mailman.7319.1150903902.27775.python-list at python.org...
Le Mercredi 21 Juin 2006 16:54, JJLaRocque at gmail.com a écrit :
> 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


In [7]: min([3, 3, 1, 3])
Out[7]: 1

In [8]: min(min(e) for e in  [ [3, 3], [3, 3, 1, 3], [3, 3, 3] ])
Out[8]: 1

regards,



Read the original posting again.  The OP does not want the minimum *value*,
but the *index* of the minimum value.

-- Paul


data = [[3,3,3,3], [3,3,3,1], [3,3,3,3]]

def getMinAndIndex(lst):
    minval,minidx = lst[0],0
    for i,v in enumerate(lst[1:]):
        if v < minval:
            minval,minidx = v,i+1
    return minval,minidx

subMins = [ getMinAndIndex(sub) for sub in data ]
subMin,subIdx = getMinAndIndex( [s[0] for s in subMins ] )

print "min = %d at [%d][%d]" % (subMin, subIdx, subMins[subIdx][1])


Gives:
min = 1 at [1][3]





More information about the Python-list mailing list