【Python】 sorted函数
来源:互联网 发布:优化采购流程 编辑:程序博客网 时间:2024/06/05 14:14
我们需要对List、Dict进行排序,Python提供了两个方法
. 对由tuple组成的List排序
Python代码
- >>> students = [('john', 'A', 15), ('jane', 'B', 12), ('dave', 'B', 10),]
用key函数排序:返回由tuple组成的list
Python代码
- >>> sorted(students, key=lambda student : student[2]) # sort by age
- [('dave', 'B', 10), ('jane', 'B', 12), ('john', 'A', 15)]
用cmp函数排序
Python代码
- >>> sorted(students, cmp=lambda x,y : cmp(x[2], y[2])) # sort by age
- [('dave', 'B', 10), ('jane', 'B', 12), ('john', 'A', 15)]
用 operator 函数来加快速度,
Python代码
- >>> from operator import itemgetter, attrgetter
- >>> sorted(students, key=itemgetter(2))
用 operator 函数进行多级排序
Python代码
- >>> sorted(students, key=itemgetter(1,2)) # sort by grade then by age
- [('john', 'A', 15), ('dave', 'B', 10), ('jane', 'B', 12)]
2. 对由字典排序 ,返回由tuple组成的List,不再是字典。
Python代码
- >>> d = {'data1':3, 'data2':1, 'data3':2, 'data4':4}
- >>> sorted(d.iteritems(), key=itemgetter(1), reverse=True)
- [('data4', 4), ('data1', 3), ('data3', 2), ('data2', 1)]
0 0
- python sorted函数使用说明
- Python的sorted函数
- python中sorted()函数
- 【Python】 sorted函数
- Python sorted函数
- python sorted()函数解析
- python sorted函数
- python内置函数 sorted
- python sorted()函数
- Python sorted() 函数
- 【Python】 sorted函数
- python sorted函数
- python 中sorted()函数
- 【Python】 sorted函数
- python sorted函数
- 【Python】 sorted函数
- Python 排序函数sorted
- Python sorted 函数
- caffe----deploy.prototxt编写版本
- 用winsw让任何Windows程序都能运行为服务
- HDU1811 Rank of Tetris(并查集+拓扑排序)
- 公告栏轮播,文字轮播
- 基数排序
- 【Python】 sorted函数
- Mybatis 大数据量的批量insert解决方案
- linux bash脚本编程知识点
- 个人模板 高精度BigInt
- [leetCode刷题笔记]2017.04.14
- zzuli 1730: 通信基站(状压DP 枚举覆盖全集的最小面积)@
- Cannot load php5apache2_4.dll into server
- 吃糖果
- 题目1039:Zero-complexity Transposition