python中sorted函數(shù)的用法是什么?一起來(lái)看看小編今天的分享吧!
sorted用法:sorted(iterable,cmp=None,key=None,reverse=False)
其中iterable指可迭代的對(duì)象;
cmp指比較函數(shù),比較什么由參數(shù)key決定;例如:cmp(e1, e2) 是具有兩個(gè)參數(shù)的比較函數(shù),返回值:負(fù)數(shù)(e1 < e2);0(e1 == e2);正數(shù)( e1 > e2)。
key指用列表元素的某個(gè)屬性或函數(shù)作為關(guān)鍵字;
reverse指排序規(guī)則,reverse=True降序,reverse=False升序(默認(rèn))。
例如:
>>>?a_dict={'A':2,'B':3,'C':4,'D':1,'E':5} >>>?sorted_a_dict?=?sorted(a_dict.items(),?key?=?lambda?x:x[1],?reverse?=?True) >>>?sorted_a_dict [('E',?5),?('C',?4),?('B',?3),?('A',?2),?('D',?1)]
表示sorted() 函數(shù)對(duì)所有可迭代的對(duì)象進(jìn)行排序操作,返回重新排序的列表;items() 方法以列表返回可遍歷的(鍵, 值) 元組數(shù)組;?lambda 構(gòu)造匿名函數(shù),以元組中第二個(gè)元素作為排序依據(jù),即x[1];?reverse = True 表示降序排列;?最后得到的 word_freq_dict 為按照頻率倒敘排列的 (鍵, 值)元組的列表。
以上就是小編今天的分享了,希望可以幫助到大家。