Sorting on multiple values, some ascending, some descending

dwelden dwoogle at gmail.com
Wed Jan 3 18:46:55 EST 2007


> The simplest way is to take advantage of sort-stability and do
> successive sorts.  For example, to sort by a primary key ascending and
> a secondary key decending:
>
>    L.sort(key=lambda r: r.secondary, reverse=True)
>    L.sort(key=lambda r: r.primary)
>
Excellent! That looks just like what I needed.

> A less general technique is to transform fields in a way that reverses
> their comparison order:
>
>   L.sort(key=lambda r: (-r.age, r.height))    # sorts descending age
> and ascending height
This one I had figured out, but could not see how to get it to work for
strings.

Much obliged.




More information about the Python-list mailing list