On this page
9.9. 运算符-标准运算符作为函数
operator模块导出一组与 Python 的固有运算符相对应的有效函数。例如,operator.add(x, y)等效于表达式x+y。函数名称是用于特殊类方法的名称。为方便起见,还提供了没有前导和尾随__的变体。
这些函数属于执行对象比较,逻辑运算,math 运算,序列运算和抽象类型测试的类别。
对象比较Function对所有对象都有用,并以它们支持的丰富比较运算符命名:
operator.lt(* a , b *)operator.le(* a , b *)operator.eq(* a , b *)operator.ne(* a , b *)operator.ge(* a , b *)operator.gt(* a , b *)operator.__lt__(* a , b *)operator.__le__(* a , b *)operator.__eq__(* a , b *)operator.__ne__(* a , b *)operator.__ge__(* a , b *)operator.__gt__(* a , b *)- 在* a 和 b *之间执行“丰富比较”。具体而言,
lt(a, b)等效于a < b,le(a, b)等效于a <= b,eq(a, b)等效于a == b,ne(a, b)等效于a != b,gt(a, b)等效于a > b,ge(a, b)等效于a >= b。请注意,与内置的cmp()不同,这些函数可以返回任何值,该值可以或可以不解释为布尔值。有关丰富比较的更多信息,请参见Comparisons。
- 在* a 和 b *之间执行“丰富比较”。具体而言,
2.2 版中的新Function。
逻辑运算通常也适用于所有对象,并支持真值测试,身份测试和布尔运算:
operator.not_(* obj *)operator.__not__(* obj *)operator.truth(* obj *)operator.is_(* a , b *)- 返回
a is b。测试对象身份。
- 返回
2.3 版的新Function。
operator.is_not(* a , b *)- 返回
a is not b。测试对象身份。
- 返回
2.3 版的新Function。
math 和按位运算是最多的:
operator.abs(* obj *)operator.__abs__(* obj *)- 返回* obj *的绝对值。
operator.add(* a , b *)operator.__add__(* a , b *)- 返回
a + b,以获得* a 和 b *数字。
- 返回
operator.and_(* a , b *)operator.__and__(* a , b *)- 返回* a 和 b *的按位与。
operator.div(* a , b *)operator.__div__(* a , b *)__future__.division无效时返回a / b。这也称为“经典”划分。
operator.floordiv(* a , b *)operator.__floordiv__(* a , b *)- 返回
a // b。
- 返回
2.2 版中的新Function。
operator.index(* a *)operator.__index__(* a *)- 返回* a *转换为整数。等效于
a.__index__()。
- 返回* a *转换为整数。等效于
2.5 版的新Function。
operator.inv(* obj *)operator.invert(* obj *)operator.__inv__(* obj *)operator.__invert__(* obj *)- 返回数字* obj *的按位倒数。这等效于
~obj。
- 返回数字* obj *的按位倒数。这等效于
2.0 版的新Function:名称invert()和invert()。
operator.lshift(* a , b *)operator.__lshift__(* a , b *)- 返回* a 向左移动 b *。
operator.mod(* a , b *)operator.__mod__(* a , b *)- 返回
a % b。
- 返回
operator.mul(* a , b *)operator.__mul__(* a , b *)- 返回
a * b,以获得* a 和 b *数字。
- 返回
operator.neg(* obj *)operator.__neg__(* obj *)- 返回* obj *否定(
-obj)。
- 返回* obj *否定(
operator.or_(* a , b *)operator.__or__(* a , b *)- 返回* a 和 b *的按位或。
operator.pos(* obj *)operator.__pos__(* obj *)- 返回* obj *正(
+obj)。
- 返回* obj *正(
operator.pow(* a , b *)operator.__pow__(* a , b *)- 返回
a ** b,以获得* a 和 b *数字。
- 返回
2.3 版的新Function。
operator.rshift(* a , b *)operator.__rshift__(* a , b *)- 返回* a 向右移动 b *。
operator.sub(* a , b *)operator.__sub__(* a , b *)- 返回
a - b。
- 返回
operator.truediv(* a , b *)operator.__truediv__(* a , b *)__future__.division有效时返回a / b。这也称为“真实”划分。
2.2 版中的新Function。
operator.xor(* a , b *)operator.__xor__(* a , b *)- 返回* a 和 b *的按位异或。
适用于序列的操作(其中一些也适用于 Map)包括:
operator.concat(* a , b *)operator.__concat__(* a , b *)- 为** a 和 b *序列返回
a + b。
- 为** a 和 b *序列返回
operator.contains(* a , b *)operator.__contains__(* a , b *)- 返回测试结果
b in a。注意相反的操作数。
- 返回测试结果
2.0 版的新Function:名称contains()。
operator.countOf(* a , b *)- 返回* a 中 b *的出现次数。
operator.delitem(* a , b *)operator.__delitem__(* a , b *)- 删除索引* b 处的 a *值。
operator.delslice(* a , b , c *)operator.__delslice__(* a , b , c *)- 从索引* b 删除 a 的切片到索引 c-1 *。
自 2.6 版起不推荐使用:此Function在 Python 3.x 中已删除。将delitem()与切片索引一起使用。
operator.getitem(* a , b *)operator.__getitem__(* a , b *)- 在索引* b 处返回 a *的值。
operator.getslice(* a , b , c *)operator.__getslice__(* a , b , c *)- 将* a 的片段从索引 b 返回到索引 c-1 *。
自 2.6 版起不推荐使用:此Function在 Python 3.x 中已删除。将getitem()与切片索引一起使用。
operator.indexOf(* a , b *)- 返回* a 中第一次出现 b *的索引。
operator.repeat(* a , b *)operator.__repeat__(* a , b *)- 从 2.7 版开始不推荐使用:改为使用mul()。
返回a * b,其中* a 是一个序列, b *是一个整数。
operator.sequenceIncludes( ... )- 自 2.0 版起弃用:改为使用contains()。
contains()的别名。
operator.setitem(* a , b , c *)operator.__setitem__(* a , b , c *)- 将索引* b 处的 a 值设置为 c *。
operator.setslice(* a , b , c , v *)operator.__setslice__(* a , b , c , v *)- 将从索引* b 到索引 c-1 的 a 切片设置为序列 v *。
自 2.6 版起不推荐使用:此Function在 Python 3.x 中已删除。将setitem()与切片索引一起使用。
使用运算符Function的示例:
>>> # Elementwise multiplication
>>> map(mul, [0, 1, 2, 3], [10, 20, 30, 40])
[0, 20, 60, 120]
>>> # Dot product
>>> sum(map(mul, [0, 1, 2, 3], [10, 20, 30, 40]))
200
许多操作都有“就地”版本。与通常的语法相比,以下函数提供了对原位运算符的更原始的访问;例如statement x += y等效于x = operator.iadd(x, y)。换句话说,z = operator.iadd(x, y)等效于复合语句z = x; z += y。
operator.iadd(* a , b *)operator.__iadd__(* a , b *)a = iadd(a, b)等效于a += b。
2.5 版的新Function。
operator.iand(* a , b *)operator.__iand__(* a , b *)a = iand(a, b)等效于a &= b。
2.5 版的新Function。
operator.iconcat(* a , b *)operator.__iconcat__(* a , b *)- 对于* a 和 b *序列,
a = iconcat(a, b)等效于a += b。
- 对于* a 和 b *序列,
2.5 版的新Function。
operator.idiv(* a , b *)operator.__idiv__(* a , b *)- 当
__future__.division无效时,a = idiv(a, b)等效于a /= b。
- 当
2.5 版的新Function。
operator.ifloordiv(* a , b *)operator.__ifloordiv__(* a , b *)a = ifloordiv(a, b)等效于a //= b。
2.5 版的新Function。
operator.ilshift(* a , b *)operator.__ilshift__(* a , b *)a = ilshift(a, b)等效于a <<= b。
2.5 版的新Function。
operator.imod(* a , b *)operator.__imod__(* a , b *)a = imod(a, b)等效于a %= b。
2.5 版的新Function。
operator.imul(* a , b *)operator.__imul__(* a , b *)a = imul(a, b)等效于a *= b。
2.5 版的新Function。
operator.ior(* a , b *)operator.__ior__(* a , b *)a = ior(a, b)等效于a |= b。
2.5 版的新Function。
operator.ipow(* a , b *)operator.__ipow__(* a , b *)a = ipow(a, b)等效于a **= b。
2.5 版的新Function。
operator.irepeat(* a , b *)operator.__irepeat__(* a , b *)- 从 2.7 版开始不推荐使用:改为使用imul()。
a = irepeat(a, b)等效于a *= b,其中* a 是一个序列, b *是一个整数。
2.5 版的新Function。
operator.irshift(* a , b *)operator.__irshift__(* a , b *)a = irshift(a, b)等效于a >>= b。
2.5 版的新Function。
operator.isub(* a , b *)operator.__isub__(* a , b *)a = isub(a, b)等效于a -= b。
2.5 版的新Function。
operator.itruediv(* a , b *)operator.__itruediv__(* a , b *)__future__.division有效时,a = itruediv(a, b)等效于a /= b。
2.5 版的新Function。
operator.ixor(* a , b *)operator.__ixor__(* a , b *)a = ixor(a, b)等效于a ^= b。
2.5 版的新Function。
operator模块还定义了一些谓词来测试对象的类型。但是,这些都不都是可靠的。最好改为测试抽象 Base Class(有关详细信息,请参见collections和numbers)。
operator.isCallable(* obj *)- 自 2.0 版起弃用:改为使用
isinstance(x, collections.Callable)。
- 自 2.0 版起弃用:改为使用
如果对象* obj *可以像函数一样调用,则返回 true;否则返回 false。对于支持call()方法的函数,绑定和未绑定方法,类对象和实例对象,返回 True。
operator.isMappingType(* obj *)- 从 2.7 版开始不推荐使用:改为使用
isinstance(x, collections.Mapping)。
- 从 2.7 版开始不推荐使用:改为使用
如果对象* obj *支持 Map 接口,则返回 true。这对于字典和所有定义getitem()的实例对象都是如此。
operator.isNumberType(* obj *)- 从 2.7 版开始不推荐使用:改为使用
isinstance(x, numbers.Number)。
- 从 2.7 版开始不推荐使用:改为使用
如果对象* obj *表示数字,则返回 true。对于用 C 实现的所有数字类型都是如此。
operator.isSequenceType(* obj *)- 从 2.7 版开始不推荐使用:改为使用
isinstance(x, collections.Sequence)。
- 从 2.7 版开始不推荐使用:改为使用
如果对象* obj *支持序列协议,则返回 true。对于在 C 中定义序列方法的所有对象以及定义getitem()的所有实例对象,此方法返回 true。
operator模块还定义了用于通用属性和项目查找的工具。这些对于将快速字段提取器用作map(),sorted(),itertools.groupby()或需要函数参数的其他函数的参数很有用。
operator.attrgetter(* attr *)operator.attrgetter(“ **” *)- 返回从其操作数获取* attr *的可调用对象。如果请求多个属性,则返回一个 Tuples。属性名称也可以包含点。例如:
在
f = attrgetter('name')之后,呼叫f(b)返回b.name。在
f = attrgetter('name', 'date')之后,呼叫f(b)返回(b.name, b.date)。在
f = attrgetter('name.first', 'name.last')之后,呼叫f(b)返回(b.name.first, b.name.last)。
Equivalent to:
def attrgetter(*items):
if len(items) == 1:
attr = items[0]
def g(obj):
return resolve_attr(obj, attr)
else:
def g(obj):
return tuple(resolve_attr(obj, attr) for attr in items)
return g
def resolve_attr(obj, attr):
for name in attr.split("."):
obj = getattr(obj, name)
return obj
2.4 版的新Function。
在版本 2.5 中进行了更改:添加了对多个属性的支持。
在 2.6 版中进行了更改:添加了对点属性的支持。
operator.itemgetter(* item *)operator.itemgetter(*个)- 返回使用操作数的getitem()方法从其操作数中获取* item *的可调用对象。如果指定了多个项目,则返回查找值的 Tuples。例如:
在
f = itemgetter(2)之后,呼叫f(r)返回r[2]。在
g = itemgetter(2, 5, 3)之后,呼叫g(r)返回(r[2], r[5], r[3])。
Equivalent to:
def itemgetter(*items):
if len(items) == 1:
item = items[0]
def g(obj):
return obj[item]
else:
def g(obj):
return tuple(obj[item] for item in items)
return g
这些项目可以是操作数的getitem()方法接受的任何类型。字典接受任何可哈希值。列表,Tuples 和字符串接受索引或切片:
>>> itemgetter(1)('ABCDEFG')
'B'
>>> itemgetter(1,3,5)('ABCDEFG')
('B', 'D', 'F')
>>> itemgetter(slice(2,None))('ABCDEFG')
'CDEFG'
2.4 版的新Function。
在版本 2.5 中进行了更改:添加了对多项目提取的支持。
使用itemgetter()从 TuplesLogging 检索特定字段的示例:
>>> inventory = [('apple', 3), ('banana', 2), ('pear', 5), ('orange', 1)]
>>> getcount = itemgetter(1)
>>> map(getcount, inventory)
[3, 2, 5, 1]
>>> sorted(inventory, key=getcount)
[('orange', 1), ('banana', 2), ('apple', 3), ('pear', 5)]
operator.methodcaller(* name * [,* args ... *])- 返回一个可调用对象,该对象在其操作数上调用方法* name *。如果给出了其他参数和/或关键字参数,它们也将被赋予方法。例如:
在
f = methodcaller('name')之后,呼叫f(b)返回b.name()。在
f = methodcaller('name', 'foo', bar=1)之后,呼叫f(b)返回b.name('foo', bar=1)。
Equivalent to:
def methodcaller(name, *args, **kwargs):
def caller(obj):
return getattr(obj, name)(*args, **kwargs)
return caller
2.6 版的新Function。
9.9.1. 将运算符 Map 到函数
下表显示了抽象运算如何与 Python 语法中的运算符和operator模块中的函数相对应。
| 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 |
div(a, b)(无__future__.division) |
| Division | a / b |
truediv(a, b)(使用__future__.division) |
| Division | a // b |
floordiv(a, b) |
| Bitwise And | a & b |
and_(a, b) |
| 按位异或 | 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) |
| Negation (Arithmetic) | - a |
neg(a) |
| Negation (Logical) | not a |
not_(a) |
| Positive | + a |
pos(a) |
| Right Shift | a >> b |
rshift(a, b) |
| Sequence Repetition | seq * i |
repeat(seq, i) |
| 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) |