13

You can sort an array of myclass by using the key argument to the sorted function:

sortedlist = sorted(myclasses, key=lambda obj: obj.myproperty)

Is there a way to define a natural ordering for our class? Perhaps some magic method so that we don't have to pass in a key each time?

e.g.,

class myclass:
    def __init__(self,a,b):
        self.key1 = a
        self.key2 = b

    def __sortkey__(self):
        return self.key2

Or will it naturally work if we define __le__ perhaps?

4

3 回答 3

17

除此之外__cmp__,您还可以使用所谓的“丰富的比较运算符” __eq__、、、、__le__和。您可以在 2.7+/3.1+ 中使用类装饰器,而不是定义所有这些。在 3.x 中消失了。__lt____gt____ge__functools.total_ordering__cmp__

于 2012-07-28T23:12:55.080 回答
3

I'd do it by overriding __cmp__

class myclass:
    def __init__(self,a,b):
        self.key1 = a
        self.key2 = b

    def __cmp__(self, other):
        return cmp(self.key2, other.key2)
于 2012-07-28T23:09:21.497 回答
3

请参阅上一个问题。答案是你可以只使用__lt__,但最好使用functools.total_ordering

于 2012-07-28T23:13:34.940 回答