Sorting on multiple values, some ascending, some descending
Neil Cerutti
horpner at yahoo.com
Thu Jan 4 13:13:10 EST 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)
>>>> shuffle(items)
>>>> count = 0
>>>> def key(value):
> ... global count
> ... count += 1
> ... return abs(value)
> ...
>>>> items.sort(key=key)
>>>> count
> 15
Thanks for the correction! That's very useful information.
--
Neil Cerutti
More information about the Python-list
mailing list