Reputation: 282865
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?
Upvotes: 16
Views: 17076
Reputation: 37441
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)
Update:
In python3, __cmp__
is gone.
Use __lt__
instead
Upvotes: 4
Reputation: 251373
See this previous question. The answer is that you can get away with just using __lt__
, but it's better to use functools.total_ordering
.
Upvotes: 3
Reputation: 28846
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.
Upvotes: 20