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/

Python中使用operator模块实现对象的多级排序的更多相关文章

  1. Python中的logging模块

    http://python.jobbole.com/86887/ 最近修改了项目里的logging相关功能,用到了python标准库里的logging模块,在此做一些记录.主要是从官方文档和stack ...

  2. 浅析Python中的struct模块

    最近在学习python网络编程这一块,在写简单的socket通信代码时,遇到了struct这个模块的使用,当时不太清楚这到底有和作用,后来查阅了相关资料大概了解了,在这里做一下简单的总结. 了解c语言 ...

  3. python中的StringIO模块

    python中的StringIO模块 标签:python StringIO 此模块主要用于在内存缓冲区中读写数据.模块是用类编写的,只有一个StringIO类,所以它的可用方法都在类中.此类中的大部分 ...

  4. python中的select模块

    介绍: Python中的select模块专注于I/O多路复用,提供了select  poll  epoll三个方法(其中后两个在Linux中可用,windows仅支持select),另外也提供了kqu ...

  5. Python中的re模块--正则表达式

    Python中的re模块--正则表达式 使用match从字符串开头匹配 以匹配国内手机号为例,通常手机号为11位,以1开头.大概是这样13509094747,(这个号码是我随便写的,请不要拨打),我们 ...

  6. 【转】浅析Python中的struct模块

    [转]浅析Python中的struct模块 最近在学习python网络编程这一块,在写简单的socket通信代码时,遇到了struct这个模块的使用,当时不太清楚这到底有和作用,后来查阅了相关资料大概 ...

  7. python中的logger模块

    logger 提供了应用程序可以直接使用的接口handler将(logger创建的)日志记录发送到合适的目的输出filter提供了细度设备来决定输出哪条日志记录formatter决定日志记录的最终输出 ...

  8. Python入门之Python中的logging模块

    基本用法 下面的代码展示了logging最基本的用法. import logging import sys # 获取logger实例,如果参数为空则返回root logger logger = log ...

  9. 深入理解python中的select模块

    简介 Python中的select模块专注于I/O多路复用,提供了select  poll  epoll三个方法(其中后两个在Linux中可用,windows仅支持select),另外也提供了kque ...

随机推荐

  1. Factors of Factorial AtCoder - 2286 (N的阶乘的因子个数)(数论)

    Problem Statement You are given an integer N. Find the number of the positive divisors of N!, modulo ...

  2. T-shirt buying CodeForces - 799B (小根堆+STL)

    题目链接 思路: 由于题目说了只有1,2,3,三种色号的衣服,然后开三个对应色号的小根堆, 我是根据pair<int,int> 创建了一个以价格小的优先的优先队列. pair中的另外一个i ...

  3. 使用matplotlib画饼图

    import matplotlib.pyplot as pltx = [4, 9, 21, 55, 30, 18]labels = ['math', 'history', 'chemistry', ' ...

  4. CNZZ友盟访问明细的采集办法

    www.cnzz.com是中文网站统计分析平台,很多站长需要获取网站提供的访问明细,以做分析. 直接采集这个网站的数据相当麻烦,通过浏览器或者fiddlercore就简单多了. 2.0新版,通过浏览器 ...

  5. 计算Java List中的重复项出现次数

    import java.util.ArrayList;import java.util.HashMap;import java.util.Iterator;import java.util.List; ...

  6. p86商空间也是Banach空间

    1.为什么要引入Zk? 2.为什么这个等式成立,和为什么要引入uk? 3.为什么为什么等于0? 属于M,则商空间是0元,p128最上面的第二个笔记

  7. Python_迭代器、生成器、列表推导式,生成器表达式

    1.迭代器 (1)可迭代对象 s1 = ' for i in s1: print(i) 可迭代对象 示例结果: D:\Python36\python.exe "E:/Python/课堂视频/ ...

  8. 【转】Word之表格、图片的题注(抬头)自动编号

    问:word中的表格怎么自动插入题注(即表头的编号自动编号)? 答: 1首先搞清楚自动编号的意思.自动插入题注的意思是,在你在word中新建或者复制一个word表格的时候,表头的编号就自动生成了,而不 ...

  9. 转:Linux下查看tomcat占用端口

    https://blog.csdn.net/liufuwu1/article/details/71123597[root@server-crm mysql]# ps -ef | grep " ...

  10. Linux 查找文件命令 find whereis locate

    Linux 有三个查找文件的命令:find, whereis, locate 其中find 不常用,whereis与locate经常使用,因为find命令速度较慢,因为whereis与locate是利 ...