Python uses the operator module to implement multi-level sorting of objects.
Preface
Recently, I encountered a small Sorting Problem in my work. I had to sort by multiple attributes of nested objects. So I found that the operator module and sorted function combination in Python can implement this function. This article describes how to use the operator module in Python to implement multi-level object sorting and share the content for your reference. The following describes the details:
For example, if I have the following class relationships, object A references an object B,
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)
The following is the sorting code for testing. Here, the sorting is based on the attr2 and attr3 attributes of embedded object B of object.
from operator import itemgetter, attrgettera1 = 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 test and the result is as follows:
[[u1, AAA, 100], [u3, BBB, 10], [u2, BBB, 100]][[u2, BBB, 100], [u3, BBB, 10], [u1, AAA, 100]]
Then, if I want to sort B. attr2 in the forward order and B. attr3 in the reverse order, we can use the following combination:
s = sorted(aaa, key=attrgetter('b.attr3'), reverse=True)s = sorted(s, key=attrgetter('b.attr2'))print s
The running result is as follows:
[[u1, AAA, 100], [u2, BBB, 100], [u3, BBB, 10]]
Summary
The above is all the content of this article. I hope the content of this article will help you in your study or work. If you have any questions, please leave a message, thank you for your support.