python中sorted函数的详细使用方法

sorted(iterable,cmp,key,reverse)

参数:iterable可以是list或者iterator;

cmp是带两个参数的比较函数;

key 是带一个参数的函数;

reverse为False或者True;

cmp比较

	>>> 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的详细使用方法

key比较

>>> 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)]

 

用reverse排序

就相当于反顺序排列

>>> sorted(list1,reverse = True)
[('sara', 80), ('mary', 90), ('lily', 95), ('david', 90)]

operator.itemgetter函数排序

>>> 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)]

 

你可能感兴趣的:(python,python,sorted)