In addition to the solution you accepted, you could also implement the special __lt__()
("less than") method on the class. The sort()
method (and the sorted()
function) will then be able to compare the objects, and thereby sort them. This works best when you will only ever sort them on this attribute, however.
class Foo(object):
def __init__(self, score):
self.score = score
def __lt__(self, other):
return self.score < other.score
l = [Foo(3), Foo(1), Foo(2)]
l.sort()
import operator
sorted_x = sorted(x, key=operator.attrgetter('score'))
if you want to sort x in-place, you can also:
x.sort(key=operator.attrgetter('score'))
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