sort problem

Alex Martelli aleaxit at yahoo.com
Fri Oct 21 21:21:46 EDT 2005


Michele Petrazzo <michele.petrazzo at TOGLIunipex.it> wrote:

> Lasse Vågsæther Karlsen wrote:
> > How about:
> > 
> > list.sort(key=lambda x: x[3])
> > 
> > Does that work?
> 
> Yes, on my linux-test-box it work, but I my developer pc I don't have
> the 2.4 yet. I think that this is a good reason for update :)

Updating is a good idea, and will let you get even faster by avoiding
the lambda:

import operator

thelist.sort(key=operator.itemgetter(3))

However, until you can upgrade you might be happy enough with a direct
implementation of the decorate-sort-undecorate (DSU) idiom which they
new "key=" named argument to sort implements.  To wit:

aux = [ (x[3], x) for x in thelist ]
aux.sort()
thelist[:] = [ x[-1] for x in aux ]

Note that the "decoration" can include as many "columns" as you want,
transformations obtained by calling int(...) or str(...) on some of the
columns, and so on.  This applies to "key=" in 2.4 just as well as to
the (slightly slower) direct implementation in 2.3 and earlier.


Alex



More information about the Python-list mailing list