Sorting on multiple values, some ascending, some descending

George Sakkis george.sakkis at gmail.com
Wed Jan 3 15:24:18 EST 2007


dwelden 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?

You got already some good replies; here's yet another less-than-optimal
way:

class revstr(str):
    def __lt__(self, other):
        return str.__gt__(self,other)
    def __gt__(self, other):
        return str.__lt__(self,other)

L.sort(key=lambda i: (i.somestring, revstr(i.someotherstring),
i.anotherkey))


George




More information about the Python-list mailing list