sorted排序
1. operator函數
在介紹sorted函數之前需要了解一下operator函數。
operator函數是python的內置函數,提供了一系列常用的函數操作
比如,operator.mul(x, y)等於x+y
這里只介紹它的itemgetter() 方法,更多的介紹可參考官網。
operator — Standard operators as functions
operator模塊提供的itemgetter函數用於獲取對象的哪些維的數據,參數為一些序號(即需要獲取的數據在對象中的序號),下面看例子。
- a = [1,2,3]
- >>> b=operator.itemgetter(1) //定義函數b,獲取對象的第1個域的值
- >>> b(a)
- 2
- >>> b=operator.itemgetter(1,0) //定義函數b,獲取對象的第1個域和第0個的值
- >>> b(a)
- (2, 1)
2. sorted函數
函數介紹:Built-in Function
官網示例:Sorting HOW TO?
函數原型:sorted(iterable[, cmp[, key[, reverse]]])
Return a new sorted list from the items in iterable.(會返回一個重新排列好的list)
iterable(可迭代):可以是list也可以是dict
cmp:可以自定義比較規則,這里不詳細敘述
key:用於比較的值
reverse:指定是順序還是逆序
下面以dict排序為例做講解:
- c = {'a': 15, 'ab': 6, 'bc': 16, 'da': 95}
-
- d = sorted(c.iteritems(),key=operator.itemgetter(0),reverse=True)
- >>> [('da', 95), ('bc', 16), ('ab', 6), ('a', 15)]
-
- e = sorted(c.iteritems(),key=operator.itemgetter(0),reverse=True)
- >>>['da', 'bc', 'a', 'ab']
1.注意區分dict加與不加iteritems() 對於結果的影響
2.我們的key選擇的是傳入參數的第0號元素,在這里即是鍵(keys),所以最終的排序是按照鍵排序,我們也可以以值作為標准進行排序,看下面示例
- d = sorted(c.iteritems(),key=operator.itemgetter(1),reverse=True)
- >>> [('da', 95), ('bc', 16), ('a', 15), ('ab', 6)]
看到這你會不會覺得operator的itemgetter函數可以用lambda函數實現:我們可以將上面的示例改成lambda
- d = sorted(c.iteritems(),key=lambda x:x[1],reverse=True)
- >>> [('da', 95), ('bc', 16), ('a', 15), ('ab', 6)]
你看結果是一樣一樣的。
文章參考:
Python中的sorted函數以及operator.itemgetter函數
python中的operator庫