How to do double sorting inside an array?

I do not know if an 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 

The bar array contains objects of type foo. I want to sort an array in descending order according to two attributes. attrb1 first

 bar.sort(key=foo.sort,reverse=True) 

Then I want to sort the sorted items inside myself according to attrb2 . So, for the 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?

+4
source share
4 answers
 bar.sort(key=lambda x: (x.attrb1, x.attrb2), reverse=True) 

And you do not need to define foo.sort

+7
source

You are already using classes, so just implement __lt__ :

 class foo: def __init__(self,a1,a2): self.attrb1 = a1 self.attrb2 = a2 # just for convenience in `__lt__` def defaultorder(self): return self.attrb1, self.attrb2 # answers `self < other`, used by the sorting algorithm def __lt__(self, other): return self.defaultorder() < other.defaultorder() bar.sort(reverse=True) 
+2
source

Sort already does this if you have a tuple of values. If you change the sorting of the method to return the tuple:

  class foo: def __init__(self,a1,a2): self.attrb1 = a1 self.attrb2 = a2 def sort(self): return self.attrb1, self.attrb2 

Then the solution is really simple:

bar.sort (key = foo.sort, reverse = True)

+1
source

You can also do this without lambda (which I personally don't like):

 import operator bar.sort(key=operator.attrgetter("attrb1","attrb2")) 

operator.attrgetter works as follows:

 a = foo(3,4) b = operator.attrgetter("attrb1","attrb2")(a) print(b) # You get (3,4) 
+1
source

Source: https://habr.com/ru/post/1336581/


All Articles