sorted(iterable,cmp,key,reverse)
参数:iterable可以是list或者iterator;
cmp是带两个参数的比较函数;
key 是带一个参数的函数;
reverse为False或者True;
>>> list1 = [('david', 90), ('mary',90), ('sara',80),('lily',95)]
>>> sorted(list1,cmp = lambda x,y: cmp(x[0],y[0]))
[('david', 90), ('lily', 95), ('mary', 90), ('sara', 80)]
>>> sorted(list1,cmp = lambda x,y: cmp(x[1],y[1]))
[('sara', 80), ('david', 90), ('mary', 90), ('lily', 95)]
在cmp与key中都是用了lambda,了解lambda的详细使用方法
>>> list1 = [('david', 90), ('mary',90), ('sara',80),('lily',95)]
>>> sorted(list1,key = lambda list1: list1[0])
[('david', 90), ('lily', 95), ('mary', 90), ('sara', 80)]
>>> sorted(list1,key = lambda list1: list1[1])
[('sara', 80), ('david', 90), ('mary', 90), ('lily', 95)]
就相当于反顺序排列
>>> sorted(list1,reverse = True)
[('sara', 80), ('mary', 90), ('lily', 95), ('david', 90)]
>>> from operator import itemgetter
>>> sorted(list1, key=itemgetter(1))
[('sara', 80), ('david', 90), ('mary', 90), ('lily', 95)]
>>> sorted(list1, key=itemgetter(0))
[('david', 90), ('lily', 95), ('mary', 90), ('sara', 80)]
介绍operator.itemgetter函数
>>> import operator
>>> a = [1,2,3]
>>> b = operator.itemgetter(0)
>>> b(a)
1
如果想要实现多级排序的话
>>> sorted(list1, key=itemgetter(0,1))
[('david', 90), ('lily', 95), ('mary', 90), ('sara', 80)]