I don't know the exact term exists for this type of sorting. Here is the problem -
I have a class foo
class foo:
def __init__(self,a1,a2):
self.attrb1 = a1
self.attrb2 = a2
def sort(self):
return self.attrb1
An array "bar" contain objects of type foo. I want to sort the array in descending order according to the two attributes. First by attrb1
bar.sort(key=foo.sort,reverse=True)
Then I want to sort the sorted elements within themselves according to attrb2
. So for two elements foo1 and foo2 in the array we have -
foo1 > foo2
if foo1.attrb1 > foo2.attrb1
elif foo1.attrb1 == foo2.attrb1
foo1.attrb2 > foo2.attrb2
How can I do this?
bar.sort(key=lambda x: (x.attrb1, x.attrb2), reverse=True)
And you don't need to define foo.sort
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