python sorted

如题所述

python sorted是怎样的呢?下面就让我们一起来了解一下吧:
sorted是属于python下的一个函数,sorted()函数是用于对所有可迭代的对象进行排序操作。
它与sort 是有一定区别的,具体的区别是:
sort通常是应用在list上的方法,而sorted则能够对所有可迭代的对象进行排序操作。
list中的sort方法一般返回的是对已经存在的列表进行操作,无返回值,但是内建函数sorted方法返回的是一个新的list,因此它并不是在原有的基础上进行操作。
语法格式:
sorted(iterable, cmp=None, key=None, reverse=False)
参数:
iterable -- 可迭代对象。
cmp -- 比较的函数,这个具有两个参数,参数的值都是从可迭代对象中取出,此函数必须遵守的规则为,大于则返回1,小于则返回-1,等于则返回0。
key -- 主要是用来进行比较的元素,只有一个参数,具体的函数的参数就是取自于可迭代对象中,指定可迭代对象中的一个元素来进行排序。
reverse -- 排序规则,reverse = True 降序 , reverse = False 升序(默认)。
参考范例:
a=[5,7,6,3,4,1,2]b=sorted(a)#保留原列表a[5,7,6,3,4,1,2]b[1,2,3,4,5,6,7]L=[(b,2),(a,1),(c,3),(d,4)]sorted(L,cmp=lambdax,y:cmp(x[1],y[1]))#利用cmp函数[(a,1),(b,2),(c,3),(d,4)]sorted(L,key=lambdax:x[1])#利用key[(a,1),(b,2),(c,3),(d,4)]students=[(john,A,15),(jane,B,12),(dave,B,10)]sorted(students,key=lambdas:s[2])#按年龄排序[(dave,B,10),(jane,B,12),(john,A,15)]sorted(students,key=lambdas:s[2],reverse=True)#按降序[(john,A,15),(jane,B,12),(dave,B,10)]
温馨提示:答案为网友推荐,仅供参考