关于python:用于比较列表的函数: no __cmp__

Function to compare lists: no __cmp__

我有一个要排序的对象列表。每个对象都有一个ID,它是一个字符串列表。

所以我定义:

1
2
3
4
class MyObject(object):
    ...
    def __cmp__(self, other):
        return self.id.__cmp__(other.id)

Python(2.7)说

1
object 'list' has no attribute '__cmp__'

所以我定义了六个"丰富的比较"…但是有更好的方法吗?


如果只需要排序对象,那么在调用sorted时最好使用key参数。

1
sorted(list_of_objects, key=lambda x: x.id)

__cmp__相比,更倾向于进行充分的比较,这就是list没有__cmp__的原因。

在您的特定情况下,您可以使用cmp函数,它将为您执行所有比较:

1
return cmp(self.id, other.id)

顺便说一下,不需要定义所有六个运算符。

If the object on the left side of the operator does not define an
appropriate rich comparison operator (either at the C level or
with one of the special methods), then the comparison is reversed,
and the right hand operator is called with the opposite operator,
and the two objects are swapped. This assumes that a < b and b > a
are equivalent, as are a <= b and b >= a, and that == and != are
commutative (e.g. a == b if and only if b == a).