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__' |
所以我定义了六个"丰富的比较"…但是有更好的方法吗?
如果只需要排序对象,那么在调用
1 | sorted(list_of_objects, key=lambda x: x.id) |
与
在您的特定情况下,您可以使用
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 area <= b andb >= a , and that== and!= are
commutative (e.g.a == b if and only ifb == a ).