Second python program: classes, sorting

Peter Otten __peter__ at web.de
Sun Aug 10 15:50:48 EDT 2008


WP wrote:

> I solved it, I rewrote __cmp__ to:
> def __cmp__(self, other):
>     if self.score == other.score:
>        return cmp(self.name, other.name)
>     else:
>        return cmp(other.score, self.score)

You can simplify that to

def __cmp__(self, other):
    return cmp(other.score, self.score) or cmp(self.name, other.name)

Alternatively you can define a key function

def descending_score(s):
    return -s.score, s.name

and then use it:

scores.sort(key=descending_score)

Because list.sort() is stable sorting twice will also work:

scores.sort(key=lambda s: s.name)
scores.sort(key=lambda s: s.score, reverse=True)

Peter



More information about the Python-list mailing list