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

operator.itemgetter函數
operator模塊提供的itemgetter函數用於獲取對象的哪些維的數據,參數爲一些序號(即須要獲取的數據在對象中的序號),下面看例子。html

a = [1,2,3] 
>>> b=operator.itemgetter(1)      //定義函數b,獲取對象的第1個域的值
>>> b(a) 

>>> b=operator.itemgetter(1,0)  //定義函數b,獲取對象的第1個域和第0個的值
>>> b(a) 
(2, 1)python

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

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

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

參數解釋:排序

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

(2)cmp爲函數,指定排序時進行比較的函數,能夠指定一個函數或者lambda函數,如:get

      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全部元素的第三個域來進行排序。it

有了上面的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/。

相關文章
相關標籤/搜索