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?
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With