max() of a list of tuples

Terry Hancock hancock at anansispaceworks.com
Tue Jan 21 06:35:58 EST 2003


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

-- 
Anansi Spaceworks
http://www.anansispaceworks.com




More information about the Python-list mailing list