Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to perform double sort inside an array?

Tags:

python

sorting

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?

like image 916
Bruce Avatar asked Dec 21 '22 18:12

Bruce


1 Answers

bar.sort(key=lambda x: (x.attrb1, x.attrb2), reverse=True)

And you don't need to define foo.sort

like image 103
SilentGhost Avatar answered Jan 04 '23 22:01

SilentGhost