You can sort an array of myclass
by using the key
argument to the sorted
function:
sortedlist = sorted(myclasses, key=lambda obj: obj.myproperty)
Is there a way to define a natural ordering for our class? Perhaps some magic method so that we don't have to pass in a key each time?
e.g.,
class myclass:
def __init__(self,a,b):
self.key1 = a
self.key2 = b
def __sortkey__(self):
return self.key2
Or will it naturally work if we define __le__
perhaps?
In addition to __cmp__
, you can also do it with the so-called "rich comparison operators" __eq__
, __le__
, __lt__
, __gt__
, and __ge__
. Rather than defining all of them, you can use the functools.total_ordering
class decorator in 2.7+/3.1+. __cmp__
is gone in 3.x.
I'd do it by overriding __cmp__
class myclass:
def __init__(self,a,b):
self.key1 = a
self.key2 = b
def __cmp__(self, other):
return cmp(self.key2, other.key2)
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