Section 48.1: Itemgetter

使用 itemgetter 将字典中的键值对按值分组:

from itertools import groupby
from operator import itemgetter
adict = {'a': 1, 'b': 5, 'c': 1}

dict((i, dict(v)) for i, v in groupby(adict.items(), itemgetter(1)))
# Output: {1: {'a': 1, 'c': 1}, 5: {'b': 5}}

相当于这样的 lambda 函数(但速度更快):

dict((i, dict(v)) for i, v in groupby(adict.items(), lambda x: x[1]))

或者以第二个元素为先,第一个元素为后,对一个元组列表进行排序:

alist_of_tuples = [(5,2), (1,3), (2,2)]
sorted(alist_of_tuples, key=itemgetter(1,0))
# Output: [(2, 2), (5, 2), (1, 3)]

Itemgetter

Section 48.2: 运算符作为下位运算符的替代

对于每个下位运算符,例如 +,都有一个 operator 函数(+的函数是 operator.add):

1 + 1
# Output: 2

from operator import add
add(1, 1)
# Output: 2

尽管主要文档指出算术运算符只允许数字输入,但也可以这样做:

from operator import mul
mul('a', 10)
# Output: 'aaaaaaaaaa'

mul([3], 3)
# Output: [3, 3, 3]

运算符作为下位运算符的替代

另请参阅:Python 官方文档中从操作到操作符函数的映射。

Section 48.3: Methodcaller

替代这种明确调用方法的 lambda 函数:

alist = ['wolf', 'sheep', 'duck']
list(filter(lambda x: x.startswith('d'), alist)) # Keep only elements that start with 'd'
# Output: ['duck']

我们可以使用一个 operator 函数来实现同样的功能:

from operator import methodcaller
list(filter(methodcaller('startswith', 'd'), alist)) # Does the same but is faster.
# Output: ['duck']

Methodcaller