Sorting on multiple values, some ascending, some descending

Peter Otten __peter__ at web.de
Thu Jan 4 12:02:48 EST 2007


Neil Cerutti wrote:

> Another trick is to factor the key application out of the sort.
> This may be a good idea if when you want to minimize the number
> of times your key function is called.
> 
> The idea is to mangle the list temporarily so you can use an
> unkeyed sort, and then unmangle the sorted data. Here's a silly
> example using a phone directory that's not stored in a format
> that's easy to sort.

No need to jump through these hoops; list.sort(key=keyfunc) calls keyfunc()
exactly once per list item:

>>> from random import shuffle
>>> items = range(-5, 10)
>>> shuffle(items)
>>> count = 0
>>> def key(value):
...     global count
...     count += 1
...     return abs(value)
...
>>> items.sort(key=key)
>>> count
15

Peter



More information about the Python-list mailing list