Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

comparison function must return int, not long

Tags:

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,

Running the code above would get the error TypeError: comparison function must return int, not long. Is there another clean way to sort class objects by certain class variables?

like image 422
user299648 Avatar asked May 24 '26 03:05

user299648


2 Answers

Use the built-in cmp function: cmp(a.x, b.x)

By the way, you can also utilize the key parameter of sort:

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

which is faster.

According to wiki.python.org:

This technique is fast because the key function is called exactly once for each input record.

like image 84
satoru Avatar answered May 26 '26 15:05

satoru


I dont think you need 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,

Output:

b a c a b c