max() of a list of tuples

Erik Max Francis max at alcyone.com
Tue Jan 21 14:24:22 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 :-/

I'm suspecting if you don't understand how it works then it can't really
be too elegant :-).

The code sample constructs an enumeration of the tuples with their third
(last) element, relies on default sorting of lists (and tuples) to sort
by the first element first, picks the maximum element of that
enumeration, and then extracts the tuple associated with it.

It works, and it's arguably the right way to do it, but "elegant" isn't
the word I'd associate with it.

-- 
 Erik Max Francis / max at alcyone.com / http://www.alcyone.com/max/
 __ San Jose, CA, USA / 37 20 N 121 53 W / &tSftDotIotE
/  \ The doors of Heaven and Hell are adjacent and identical.
\__/ Nikos Kazantzakis
    Official Omega page / http://www.alcyone.com/max/projects/omega/
 The official distribution page for the popular Roguelike, Omega.




More information about the Python-list mailing list