原文链接
Python--sorted函数
. 对由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)]