python中operator.itemgetter函数
生活随笔
收集整理的這篇文章主要介紹了
python中operator.itemgetter函数
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
operator模塊提供的itemgetter函數(shù)用于獲取對象的哪些維的數(shù)據(jù),參數(shù)為一些序號(即需要獲取的數(shù)據(jù)在對象中的序號),下面看例子。
k = [3,6,8]b = operator.itemgetter(1)print(b(k))#輸出6k = [3,6,8]b = operator.itemgetter(2,0)print(b(k))#輸出(8, 3)
要注意,operator.itemgetter函數(shù)獲取的不是值,而是定義了一個函數(shù),通過該函數(shù)作用到對象上才能獲取值。
''' 遇到問題沒人解答?小編創(chuàng)建了一個Python學習交流QQ群:579817333 尋找有志同道合的小伙伴,互幫互助,群里還有不錯的視頻學習教程和PDF電子書! '''students = [('john', 'C', 15), ('jane', 'A', 12), ('dave', 'B', 10)]s = sorted(students,key = operator.itemgetter(1,2))print(s)#輸出[('jane', 'A', 12), ('dave', 'B', 10), ('john', 'C', 15)]看看下面的練習
Q:找到年齡最大的人,并輸出,person = {“l(fā)i”:18,“wang”:50,“zhang”:20,“sun”:22}
常規(guī)for循環(huán)解法
''' 遇到問題沒人解答?小編創(chuàng)建了一個Python學習交流QQ群:579817333 尋找有志同道合的小伙伴,互幫互助,群里還有不錯的視頻學習教程和PDF電子書! ''' def fun(person):max = 0name = ""for key,value in person.items():if value > max:max = valuename = keyprint(name)print(max) fun(person)利用operator.itemgetter函數(shù)
import operatorperson = {"li":18,"wang":50,"zhang":20,"sun":22}print(max(person.values()))print(max(person.items(),key = operator.itemgetter(1))[0]) # 獲取最大值的 key總結
以上是生活随笔為你收集整理的python中operator.itemgetter函数的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: python 超时重试方法
- 下一篇: Python 重写父类方法