Python USES the operator module to realize the multilevel sorting of objects

  • 2020-06-01 10:10:42
  • OfStack


Recently, I encountered a small sorting problem in my work, which required sorting by multiple properties of nested objects. Therefore, I found that the combination of operator module and sorted function in Python can realize this function. This paper introduces Python using operator module to achieve the multilevel ordering of objects related content, to share for your reference and learning, the following to see the detailed introduction:

For example, if I have the following class relationship, the A object refers to an B object,

class A(object):
 def __init__(self, b):
  self.b = b
 def __str__(self):
  return "[%s, %s, %s]" % (self.b.attr1, self.b.attr2, self.b.attr3)
 def __repr__(self):
  return "[%s, %s, %s]" % (self.b.attr1, self.b.attr2, self.b.attr3)

class B(object):
 def __init__(self, attr1, attr2, attr3):
  self.attr1 = attr1
  self.attr2 = attr2
  self.attr3 = attr3
 def __str__(self):
  return "[%s, %s, %s]" % (self.attr1, self.attr2, self.attr3)
 def __repr__(self):
  return "[%s, %s, %s]" % (self.attr1, self.attr2, self.attr3)

Here is the test sort code, sorted by the attr2 and attr3 properties of the embedded B object A.

from operator import itemgetter, attrgetter

a1 = A(B('u1', 'AAA', 100))
a2 = A(B('u2', 'BBB', 100))
a3 = A(B('u3', 'BBB', 10))
aaa = (a1, a2, a3,)

print sorted(aaa, key=attrgetter('b.attr2', 'b.attr3'))
print sorted(aaa, key=attrgetter('b.attr2', 'b.attr3') .  reverse=True)

Run the above test and the results are as follows:

[[u1, AAA, 100], [u3, BBB, 10], [u2, BBB, 100]]
[[u2, BBB, 100], [u3, BBB, 10], [u1, AAA, 100]]

So, if I need to order b.attr2 in positive order and then b.attr3 in reverse order, I can do this using the following combination:

s = sorted(aaa, key=attrgetter('b.attr3'), reverse=True)
s = sorted(s, key=attrgetter('b.attr2'))
print s

The results are as follows:

[[u1, AAA, 100], [u2, BBB, 100], [u3, BBB, 10]]


Related articles: