python operator.itemgetter

operator模块提供的itemgetter函数用于获取对象的哪些维的数据,参数为一些索引或键值。

举例:

#按升序对(名称,年龄,高度)元组进行排序
from operator import itemgetter
l = [('Jony','17','91'),('John','20','90'),('Json','21 ','85'),('Jony','17','93'),('Tom','19','80')]
print(sorted(l,key = itemgetter(0,1,2)))

#按升序对(年龄,身高)元祖进行排序
print(sorted(l,key = itemgetter(1,2)))

输出:

[('John', '20', '90'), ('Jony', '17', '91'), ('Jony', '17', '93'), ('Json', '21 ', '85'), ('Tom', '19', '80')]
[('Jony', '17', '91'), ('Jony', '17', '93'), ('Tom', '19', '80'), ('John', '20', '90'), ('Json', '21 ', '85')]

posted @ 2020-04-24 10:37  linma  阅读(402)  评论(0编辑  收藏  举报