Sort

Alex Martelli aleaxit at yahoo.com
Wed Dec 6 11:37:40 EST 2000


"Greg Landrum" <glandrum at my-deja.com> wrote in message
news:90liij$805$1 at nnrp1.deja.com...
    [snip]
> >The sort() method takes an optional argument specifying a comparison
> >function of two arguments (list items) which should return -1, 0 or 1
> >depending on whether the first argument is considered smaller than,
> >equal to, or larger than the second argument.
>
> So the answer to the original question would be:
>
> l.sort (lambda a, b : a[2] - b[2])

Not sure that works, but, according to the  docs you just quoted,
it shouldn't, as it will not return just -1 or +1 for different
a[2] and b[2].  Not to mention what happens if they're strings!-)

Rather,

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

might work better -- that's what the builtin cmp function IS
for, after all.  (But the Schwartzian Transform I already
suggested is better yet:-).

[Admittedly, cmp is NOT documented to return just -1 or +1,
as sort is documented to require, but I _dearly hope_ that
either of these IS just a glitch in the docs!-)]


Alex







More information about the Python-list mailing list