max() of a list of tuples
p-abel at t-online.de
Tue Jan 21 21:02:00 CET 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).index(max(z))] # 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.
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)
More information about the Python-list