max() of a list of tuples

Peter Abel p-abel at t-online.de
Tue Jan 21 15:02:00 EST 2003


Terry Hancock <hancock at anansispaceworks.com> wrote in message news:<ygaX9.4400$bL4.431294 at newsread2.prod.itd.earthlink.net>...
> Mario Wehbrink wrote:
> > i have a list of tuples that look like:
> > [(1,3,5), (8,16,2), (2,56,4)]
> > 
> > what i am interested, in is the tuple with the greatest value in pos 3.
> > So in this case it would be (1,3,5). Is there a way to tell
> > max(mylistoftuples) to only look at the last position of the tuples?
> 
> Don't know if this is the most elegant solution, but it does work:
> 
> l = [(1, 3, 5), (8, 16, 2), (2, 56, 4)]
> z = zip(*l)
> z  # prints [(1, 8, 2), (3, 16, 56), (5, 2, 4)]
> l[list(z[2]).index(max(z[2]))]  # prints (1, 3, 5)
> 
> Ugly, but:
> 
> * zip combines sequences into a list of tuples
> * one of these contains the sequence you want to test
> * we find the maximum and what its index in the sequence is
> * we use that to look up the index in the original list
> 
> Maybe someone will have a more elegant solution.
> 
> Cheers,
> Terry

How about this?

>>> l = [(1, 3, 5), (8, 16, 2), (2, 56, 4)]
>>> reduce(lambda y,(u,v,x):y>x and y or x,l)
(1, 3, 5)

Regards
Peter




More information about the Python-list mailing list