比较函数必须返回int,不长

时间:2013-05-25 01:55:53

标签: python sorting

class C:
    def __init__(self,n,x):
        self.n = n
        self.x = x

a = C('a',1)
b = C('b',2)
c = C('c',3)

classList = [b,a,c]

for q in classList: print q.n,

classList.sort(lambda a,b: long(a.x - b.x))

for q in classList: print q.n,

运行上面的代码会收到错误TypeError: comparison function must return int, not long。 是否有另一种干净的方法来通过某些类变量对类对象进行排序?

4 个答案:

答案 0 :(得分:7)

使用内置的cmp功能:cmp(a.x, b.x)

顺便说一下,您还可以使用key的{​​{1}}参数:

sort

更快。

根据wiki.python.org

  

这项技术很快,因为关键功能只需调用一次   对于每个输入记录。

答案 1 :(得分:1)

我认为你不需要long

class C:
    def __init__(self,n,x):
        self.n = n
        self.x = x

a = C('a',1)
b = C('b',2)
c = C('c',3)

classList = [b,a,c]

for q in classList: print q.n,

classList.sort(lambda a,b: a.x - b.x)

for q in classList: print q.n,

输出:

b a c a b c

答案 2 :(得分:1)

不使用cmp函数,而是使用key函数 - 它更有效,并且对它可以返回的类型没有这种限制:

classList.sort(key=lambda a: a.x)

这也是未来的证明:Python 3不再支持cmp函数,并且继续存在于Python 2中以支持旧代码(从key之前存在)。

答案 3 :(得分:0)

您只需将您想要的比较添加到您的课程中:

class C(object):
    def __init__(self,n,x):
        self.n = n
        self.x = x

    def __cmp__(self,other):
        return cmp(self.x,other.x)