operator模块提供的itemgetter函数用于获取对象的哪些维的数据,参数为一些序号(即需要获取的数据在对象中的序号),下面看例子。
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)]
看看下面的练习
Q:找到年龄最大的人,并输出,person = { "li":18,"wang":50,"zhang":20,"sun":22}
常规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函数
1 import operator2 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