Sorting on multiple values, some ascending, some descending
__peter__ at web.de
Thu Jan 4 18:02:48 CET 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)
>>> count = 0
>>> def key(value):
... global count
... count += 1
... return abs(value)
More information about the Python-list