歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> Python中的sorted函數以及operator.itemgetter函數

Python中的sorted函數以及operator.itemgetter函數

日期:2017/3/1 9:52:42   编辑:Linux編程

operator.itemgetter函數
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)

要注意,operator.itemgetter函數獲取的不是值,而是定義了一個函數,通過該函數作用到對象上才能獲取值。

sorted函數
Python內置的排序函數sorted可以對list或者iterator進行排序,官網文檔見:http://docs.python.org/2/library/functions.html?highlight=sorted#sorted,該函數原型為:

sorted(iterable[, cmp[, key[, reverse]]])

參數解釋:

(1)iterable指定要排序的list或者iterable,不用多說;

(2)cmp為函數,指定排序時進行比較的函數,可以指定一個函數或者lambda函數,如:

students為類對象的list,沒個成員有三個域,用sorted進行比較時可以自己定cmp函數,例如這裡要通過比較第三個數據成員來排序,代碼可以這樣寫:
students = [('john', 'A', 15), ('jane', 'B', 12), ('dave', 'B', 10)]
sorted(students, key=lambda student : student[2])
(3)key為函數,指定取待排序元素的哪一項進行排序,函數用上面的例子來說明,代碼如下:
sorted(students, key=lambda student : student[2])

key指定的lambda函數功能是去元素student的第三個域(即:student[2]),因此sorted排序時,會以students所有元素的第三個域來進行排序。

有了上面的operator.itemgetter函數,也可以用該函數來實現,例如要通過student的第三個域排序,可以這麼寫:
sorted(students, key=operator.itemgetter(2))
sorted函數也可以進行多級排序,例如要根據第二個域和第三個域進行排序,可以這麼寫:
sorted(students, key=operator.itemgetter(1,2))

即先跟句第二個域排序,再根據第三個域排序。
(4)reverse參數就不用多說了,是一個bool變量,表示升序還是降序排列,默認為false(升序排列),定義為True時將按降序排列。

sorted函數更多的例子可以參考官網文檔:https://wiki.python.org/moin/HowTo/Sorting/。

推薦閱讀:

Python學習總結—安裝與配置環境 http://www.linuxidc.com/Linux/2012-11/73912.htm

Python文件或目錄操作的常用函數 http://www.linuxidc.com/Linux/2013-09/90567.htm

Python腳本獲取Linux系統信息 http://www.linuxidc.com/Linux/2013-08/88531.htm

Python文件處理:讀取文件 http://www.linuxidc.com/Linux/2013-08/88496.htm

如何發布自定義的Python模塊 http://www.linuxidc.com/Linux/2013-08/88495.htm

Python爬蟲多線程抓取代理服務器 http://www.linuxidc.com/Linux/2013-07/87289.htm

Copyright © Linux教程網 All Rights Reserved