1. 程式人生 > >python中的operator.itemgetter函數

python中的operator.itemgetter函數

imp print uno clas art 數據 targe key src

來自:https://blog.csdn.net/dongtingzhizi/article/details/12068205

operator模塊提供的itemgetter函數用於獲取對象的哪些維的數據,參數為一些序號,看下面例子:

import operator

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

結果:2

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

結果:(2,1)

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

sorted函數

sorted(iterable[, cmp[, key[, reverse]]])
  • iterable:可叠代對象
  • cmp:cmp函數用於比較2個對象,如果 x < y 返回 -1, 如果 x == y 返回 0, 如果 x > y 返回 1。
  • key:key的參數為一個函數或者lambda函數。
  • reverse:reverse = True 降序 , reverse = False 升序(默認)。

a = [(john, A, 15), (jane, B, 12), (dave, B, 10)]
b = sorted(a, key = operator.itemgetter(2))
print(b)

技術分享圖片

python中的operator.itemgetter函數