python中operator.itemgetter函數

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

1 k = [3,6,8]
2 b = operator.itemgetter(1)
3 print(b(k))
4 #輸出6
1 k = [3,6,8]
2 b = operator.itemgetter(2,0)
3 print(b(k))
4 #輸出(8, 3)

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

1 students = [('john', 'C', 15), ('jane', 'A', 12), ('dave', 'B', 10)]
2 s = sorted(students,key = operator.itemgetter(1,2))
3 print(s)
4 #輸出[('jane', 'A', 12), ('dave', 'B', 10), ('john', 'C', 15)]

看看下面的練習spa

Q:找到年齡最大的人,並輸出,person = {"li":18,"wang":50,"zhang":20,"sun":22}code

常規for循環解法對象

 1 def fun(person):
 2     max = 0
 3     name = ""
 4     for key,value in person.items():
 5         if value > max:
 6             max = value
 7             name = key
 8     print(name)
 9     print(max)
10 fun(person)

利用operator.itemgetter函數blog

1 import operator
2 person = {"li":18,"wang":50,"zhang":20,"sun":22}
3 print(max(person.values()))
4 print(max(person.items(),key = operator.itemgetter(1))[0])  # 獲取最大值的 key
相關文章
相關標籤/搜索