Sort

Alex Martelli aleaxit at yahoo.com
Wed Dec 6 06:57:33 EST 2000


"Steve Horne" <sh at ttsoftware.co.uk> wrote in message
news:oa8s2tsls5foll62r8fpa6nlcpisb6v1ek at 4ax.com...
> On Wed, 06 Dec 2000 09:07:57 GMT, "Alfred" <scj at mcom.mcom.fr> wrote:
>
> >I'm trying to sort a List of List, on the third col, but I don't find how
to
> >do this.
>
> You can specify an alternative comparison function to the sort method.
> The easiest way to do this is with a lambda...
>
> l.sort (lambda a, b : a[2] < b[2])
>
> For comparison, the following should do the same as the basic sort
> (but slower)...
>
> l.sort (lambda a, b : a < b)

Faster for sorting a large list is a "Schwartzian Transform" approach:

    auxlist = [ (x[2], x) for x in thelist ]
    auxlist.sort()
    thelist = [ x[1] for x in auxlist ]

This does roughly the same thing as:

    thelist.sort(lambda a, b: cmp(a[2], b[2]))

but more rapidly.  ("Roughly", because: the Schwartzian Transform
approach is not in-place, which may matter if you're very tight in
memory or there are other outstanding references to thelist; also,
if two items have identical x[2] sub-items, the [random-ish] ways
in which the two approaches sort them will probably differ).


Alex






More information about the Python-list mailing list