当前位置:主页 > 软件编程 > Python代码 >

Python利用operator模块实现对象的多级排序详解

时间:2021-02-03 18:26:09 | 栏目:Python代码 | 点击:

前言

最近在工作中碰到一个小的排序问题,需要按嵌套对象的多个属性来排序,于是发现了Python里的operator模块和sorted函数组合可以实现这个功能。本文介绍了Python用operator模块实现对象的多级排序的相关内容,分享出来供大家参考学习,下面来看看详细的介绍:

比如我有如下的类关系,A对象引用了一个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)

下面是测试排序代码,这里是按照A对象的内嵌对象B的attr2和attr3属性来排序。

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)

运行上面的测试,结果如下:

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

那么,如果我需要先按b.attr2正序,再按b.attr3倒序来排序,可以使用下面组合来实现:

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

运行结果如下:

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

总结

您可能感兴趣的文章:

相关文章