[Python-Dev] decorate-sort-undecorate

Geoffrey Talvola gtalvola at nameconnector.com
Wed Oct 15 11:05:17 EDT 2003


Alex Martelli wrote:
> On Tuesday 14 October 2003 11:06 pm, Geoffrey Talvola wrote:
>    ...
>> The point I'm trying to make it that a key function is usually more
>> natural to use than a comparison function.  You're right, DSU isn't
>> the only way to 
> 
> I agree, with ONE important exception: when your desired sort order
> is e.g "primary key ascending field X, secondary key descending
> field Y", writing
> a key-extraction function can be an absolute BEAR (you have to know
> the type of field Y, and even then how to build a key that
> will sort in
> descending order by it is generally anything but easy), while
> a comparison
> function is trivial:

In this case, how about sorting twice, taking advantage of stability?  Using
the proposed new syntax:

mylist.sort(key = lambda r: r.Y)
mylist.reverse()
mylist.sort(key = lambda r: r.X)

It might actually be the fastest way for very large lists, and while it's
not immediately obvious what it's doing, it's not _that_ unreadable...

- Geoff



More information about the Python-Dev mailing list