max() of a list of tuples

Max M maxm at mxm.dk
Tue Jan 21 07:30:39 EST 2003


Mario Wehbrink wrote:
 > Am Die, 21 Jan 2003 schrieb Max M in comp.lang.python:
 >
 >
 >>Mario Wehbrink wrote:
 >>
 >>
 >>>[maximum of list of tuples]
 >>
 >>
 >>l = [(1,3,5), (8,16,2), (2,56,4)]
 >>print max([(i[-1],i) for i in l])[1]
 >>
 >> >>> (1,3,5)
 >
 > Nice and elegant! Thanks. Although i don't understand how it works :-/

Here goes then!

# wont explain this one ;-)

l = [(1,3,5), (8,16,2), (2,56,4)]

# create a new list of 2 element tuples with last element of
# your tuples as the first value, and the actual tuple as the second.
# this is a standard idiom for sorting efficiently in Python

sList = [(i[-1],i) for i in l]
# sList = [(5,(1,3,5)), (2,(8,16,2)), (4,(2,56,4))]

# Because the first element is the most significant in a compare,
# python will get max value from that

maxElement = max(sList)
# maxElement = (5,(1,3,5))

# and to get the correct tuple I take the 2. element in maxElement

print maxElement[1]

 >>> (1,3,5)

I hope that is more obvious


regards

-- 

hilsen/regards Max M

http://www.futureport.dk/
Fremtiden, videnskab, skeptiscisme og transhumanisme





More information about the Python-list mailing list