sort by last then by first
Alex Martelli
aleax at aleax.it
Wed Jan 29 09:00:23 EST 2003
Peter Abel wrote:
...
> If you change the order of sorting from
> low order key to high order key, I can't see
> any reason, why this shouldn't work stable.
the list.sort method is NOT guaranteed to be stable.
It generally LOOKS stable, for small enough lists,
up to Python 2.2 -- and it has been changed to one
that happens to be stable in 2.3 -- but it's never
a good idea to rely on such things, which may well
change from one version to another: list.sort at any
time will be the fastest sort Tim Peters can think
up, whether that's a stable one or not.
If you DO need a stable sort, see:
http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/52234
> # 1) Sort by 3rd name
>>>> l.sort(lambda a,b:cmp(a[2],b[2]))
> # 2) Sort by 2nd name
>>>> l.sort(lambda a,b:cmp(a[1],b[1]))
> # 3) Sort by 1st name
>>>> l.sort()
...
> Though I can't say anything about speed.
I can: it will be lousy. Besides, for this example, just
the "# 3)" call happens to have the same end result as
1 then 2 then 3, because sequences compare lexicographically.
The (printed) Python Cookbook's chapter on Sorting and
Searching has a lot of useful and interesting info on
such issues, particularly in Tim Peter's introduction.
Alex
More information about the Python-list
mailing list