operator模块提供的itemgetter函数用于获取对象的哪些维的数据,参数为一些序号(即需要获取的数据在对象中的序号)
要注意,operator.itemgetter函数获取的不是值,而是定义了一个函数,通过该函数作用到对象上才能获取值
根据itemgetter的值对字典的键-值对进行分组 :
from itertools import groupby from operator import itemgetter adict = {'a': 1, 'b': 5, 'c': 1} print(dict((i, dict(v)) for i, v in groupby(adict.items(), itemgetter(1)))) #itemgetter(1)即将每个字典的value值取出 # 输出: {1: {'a': 1, 'c': 1}, 5: {'b': 5}}
上面的分组代码与下面使用lambda函数等价(但上面的代码速度会更快):
dict((i, dict(v)) for i, v in groupby(adict.items(), lambda x: x[1]))
itemgetter可以将元组列表中的元素排序(下面的代码将单个元组的两个元素互换位置后逐一比较排序):
alist_of_tuples = [(5,2), (1,3), (2,2)] sorted(alist_of_tuples, key=itemgetter(1,0)) #输出: [(2, 2), (5, 2), (1, 3)]
对于每个运算符,例如+,都有一个对应的操作符函数(如add):
print(1 + 1) # 输出: 2 from operator import add print(add(1, 1)) # 输出: 2
mul乘积函数, 尽管官方文档声明此算术运算符只允许数字输入,但其实这样做是可以的:
from operator import mul print(mul('a', 10)) # 输出: 'aaaaaaaaaa' print(mul([3], 3)) # 输出: [3, 3, 3]
根据官方文档,具体各操作符及对应的操作函数如下
Operation | Syntax | Function |
---|---|---|
Addition | a + b |
add(a, b) |
Concatenation | seq1 + seq2 |
concat(seq1, seq2) |
Containment Test | obj in seq |
contains(seq, obj) |
Division | a / b |
truediv(a, b) |
Division | a // b |
floordiv(a, b) |
Bitwise And | a & b |
and_(a, b) |
Bitwise Exclusive Or | a ^ b |
xor(a, b) |
Bitwise Inversion | ~ a |
invert(a) |
Bitwise Or | a | b |
or_(a, b) |
Exponentiation | a ** b |
pow(a, b) |
Identity | a is b |
is_(a, b) |
Identity | a is not b |
is_not(a, b) |
Indexed Assignment | obj[k] = v |
setitem(obj, k, v) |
Indexed Deletion | del obj[k] |
delitem(obj, k) |
Indexing | obj[k] |
getitem(obj, k) |
Left Shift | a << b |
lshift(a, b) |
Modulo | a % b |
mod(a, b) |
Multiplication | a * b |
mul(a, b) |
Matrix Multiplication | a @ b |
matmul(a, b) |
Negation (Arithmetic) | - a |
neg(a) |
Negation (Logical) | not a |
not_(a) |
Positive | + a |
pos(a) |
Right Shift | a >> b |
rshift(a, b) |
Slice Assignment | seq[i:j] = values |
setitem(seq, slice(i, j), values) |
Slice Deletion | del seq[i:j] |
delitem(seq, slice(i, j)) |
Slicing | seq[i:j] |
getitem(seq, slice(i, j)) |
String Formatting | s % obj |
mod(s, obj) |
Subtraction | a - b |
sub(a, b) |
Truth Test | obj |
truth(obj) |
Ordering | a < b |
lt(a, b) |
Ordering | a <= b |
le(a, b) |
Equality | a == b |
eq(a, b) |
Difference | a != b |
ne(a, b) |
Ordering | a >= b |
ge(a, b) |
Ordering | a > b |
gt(a, b) |
此函数是显式调用 lambda的函数:
alist = ['wolf', 'sheep', 'duck'] print(list(filter(lambda x: x.startswith('d'), alist))) # 只保留以“d”开头的元素 # 输出: ['duck'] from operator import methodcaller print(list(filter(methodcaller('startswith', 'd'), alist))) # 效果等价,但速度更快! # 输出: ['duck']
上述代码在python3云环境中调试成功,请勿转载,谢谢