Python中使用operator模块实现对象的多级排序

本文介绍如何使用Python的operator模块和sorted函数实现对象的多级排序。通过具体示例展示了如何按照嵌套对象的多个属性进行排序,并提供了按不同属性先后顺序排序的方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Python中使用operator模块实现对象的多级排序

今天碰到一个小的排序问题,需要按嵌套对象的多个属性来排序,于是发现了Python里的operator模块和sorted函数组合可以实现这个功能。

比如我有如下的类关系,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)
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17

下面是测试排序代码,这里是按照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)
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9

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

[[u1, AAA, 100], [u3, BBB, 10], [u2, BBB, 100]]
[[u2, BBB, 100], [u3, BBB, 10], [u1, AAA, 100]]
  • 1
  • 2
 
  • 1
  • 2

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

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

运行结果如下:

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

http://mobike.365soke.cn/
http://youbai.365soke.cn/
http://qibeitech.365soke.cn/

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值