Sorting on multiple values, some ascending, some descending
horpner at yahoo.com
Thu Jan 4 19:13:10 CET 2007
On 2007-01-04, Peter Otten <__peter__ at web.de> wrote:
> 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)
Thanks for the correction! That's very useful information.
More information about the Python-list