Sorting on multiple values, some ascending, some descending

Neil Cerutti horpner at yahoo.com
Thu Jan 4 11:23:35 EST 2007


On 2007-01-03, dwelden <dwoogle at gmail.com> wrote:
> I have successfully used the sort lambda construct described in
> http://mail.python.org/pipermail/python-list/2006-April/377443.html.
> However, how do I take it one step further such that some
> values can be sorted ascending and others descending? Easy
> enough if the sort values are numeric (just negate the value),
> but what about text?
>
> Is the only option to define an external sorting function to
> loop through the list and perform the comparisons one value at
> a time?

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.

>>> a = [("Neil Cerutti", "8025552954"), ("Ted Smith", "8025552281"), ("Barny Fife", "8025551105")]
>>> b = [(" ".join(reversed(x.split())), y) for (x, y) in a]
>>> b
[('Cerutti Neil', '8025552954'), ('Smith Ted', '8025552281'), ('Fife Barny', '8025551105')]
>>> b.sort()
>>> b
[('Cerutti Neil', '8025552954'), ('Fife Barny', '8025551105'), ('Smith Ted', '8025552281')]
>>> a = [(" ".join(reversed(x.split())), y) for (x, y) in b]
>>> a
[('Neil Cerutti', '8025552954'), ('Barny Fife', '8025551105'), ('Ted Smith', '8025552281')]

-- 
Neil Cerutti
Eddie Robinson is about one word: winning and losing. --Eddie Robinson's agent
Paul Collier



More information about the Python-list mailing list