python中sorted函數的用法是什麼?一起來看看小編今天的分享吧!
sorted用法:sorted(iterable,cmp=None,key=None,reverse=False)
其中iterable指可迭代的對象;
cmp指比較函數,比較什麼由參數key決定;例如:cmp(e1, e2) 是具有兩個參數的比較函數,返回值:負數(e1 < e2);0(e1 == e2);正數( e1 > e2)。
key指用列表元素的某個屬性或函數作爲關鍵字;
reverse指排序規則,reverse=True降序,reverse=False升序(默認)。
例如:
>>> 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() 函數對所有可迭代的對象進行排序操作,返回重新排序的列表;items() 方法以列表返回可遍歷的(鍵, 值) 元組數組; lambda 構造匿名函數,以元組中第二個元素作爲排序依據,即x[1]; reverse = True 表示降序排列; 最後得到的 word_freq_dict 爲按照頻率倒敘排列的 (鍵, 值)元組的列表。