# operator.itemgetter(*items) # 获取item
>>> from operator import itemgetter # list使用下标进行返回 >>> a [('a', 1), ('b', 2), ('c', 3), ('d', 4)] >>> itemgetter(1)(a) # 获取a中下标为1的元组 ('b', 2) >>> itemgetter(1,3)(a) # 同时获取多个元组 (('b', 2), ('d', 4)) # dict使用键来返回 >>> a = {'one': 1, 'two':2, 'three':3} >>> itemgetter('one')(a) 1 >>> itemgetter('one', 'two')(a) (1, 2)
# 使用attrgetter()获取其属性
# 《python cookbook》 书籍的例子
from operator import attrgetter class User(object): def __init__(self, uid): self.uid = uid def __repr__(self): return 'User({})'.format(self.uid) users = [User(25), User(14), User(100)] print(sorted(users, key=attrgetter('uid'))) """ D:笔记python电子书Python3>python index.py [User(14), User(25), User(100)] """
# 使用attrgetter可以使用lambda来进行代替:
class User(object): def __init__(self, uid): self.uid = uid def __repr__(self): return 'User({})'.format(self.uid) users = [User(25), User(14), User(100)] print(sorted(users, key=lambda u: u.uid)) """ D:笔记python电子书Python3>python index.py [User(14), User(25), User(100)] """
《python cookbook》书籍中提到attrgetter()的速度相对来说比lambda快一些,具体可使用pytest进行测试,这里不做详细测试