Sorting of list containing tuples

Christoph Haas email at christoph-haas.de
Thu May 18 15:55:29 EDT 2006


On Thu, May 18, 2006 at 09:52:39PM +0200, Christoph Haas wrote:
> On Thu, May 18, 2006 at 12:38:55PM -0700, Paul Rubin wrote:
> > Ronny Mandal <ronnyma at math.uio.no> writes:
> > > And now I want to sort l reverse by the second element in the tuple,
> > > i.e the result should ideally be:
> > > 
> > >  l = [(6,5),(2,3),(3,2)]
> > 
> > sorted(l, key = lambda a: -a[1])
> 
> Or in Python <2.4:
> 
> l.sort(lambda x,y: x[1]-y[1])
> 
> (Although that's not technically perfect. Sort expect a function that
> returns -1, 0 or 1. Here we get positive integers and negative
> integers. YMMV.)

Crap... why do I always forget about cmp()? :)

This should be it:

l.sort(lambda x,y: cmp(x[1],y[1]))

Kindly
 Christoph




More information about the Python-list mailing list