On this page
运算符-标准运算符作为函数
源代码: Lib/operator.py
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
。请注意,这些函数可以返回任何值,该值可以或可以不解释为布尔值。有关丰富比较的更多信息,请参见Comparisons。
- 在* a 和 b *之间执行“丰富比较”。具体而言,
逻辑运算通常也适用于所有对象,并支持真值测试,身份测试和布尔运算:
operator.
not_
(* obj *)operator.
__not__
(* obj *)operator.
truth
(* obj *)operator.
is_
(* a , b *)- 返回
a is b
。测试对象身份。
- 返回
operator.
is_not
(* a , b *)- 返回
a is not b
。测试对象身份。
- 返回
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.
floordiv
(* a , b *)operator.
__floordiv__
(* a , b *)- 返回
a // b
。
- 返回
operator.
index
(* a *)operator.
__index__
(* a *)- 返回* a *转换为整数。等效于
a.__index__()
。
- 返回* a *转换为整数。等效于
operator.
inv
(* obj *)operator.
invert
(* obj *)operator.
__inv__
(* obj *)operator.
__invert__
(* obj *)- 返回数字* obj *的按位倒数。这等效于
~obj
。
- 返回数字* obj *的按位倒数。这等效于
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.
matmul
(* a , b *)operator.
__matmul__
(* a , b *)- 返回
a @ b
。
- 返回
3.5 版中的新Function。
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 *数字。
- 返回
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 *)- 返回
a / b
,其中 2/3 是.66 而不是 0.这也称为“ true”除法。
- 返回
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
。注意相反的操作数。
- 返回测试结果
operator.
countOf
(* a , b *)- 返回* a 中 b *的出现次数。
operator.
delitem
(* a , b *)operator.
__delitem__
(* a , b *)- 删除索引* b 处的 a *值。
operator.
getitem
(* a , b *)operator.
__getitem__
(* a , b *)- 在索引* b 处返回 a *的值。
operator.
indexOf
(* a , b *)- 返回* a 中第一次出现 b *的索引。
operator.
setitem
(* a , b , c *)operator.
__setitem__
(* a , b , c *)- 将索引* b 处的 a 值设置为 c *。
operator.
length_hint
(* obj , default = 0 *)- 返回对象* o *的估计长度。首先try返回其实际长度,然后使用object.length_hint()进行估算,最后返回默认值。
3.4 版的新Function。
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 any(not isinstance(item, str) for item in items):
raise TypeError('attribute name must be a string')
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
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('name')({'name': 'tu', 'age': 18})
'tu'
>>> itemgetter(1)('ABCDEFG')
'B'
>>> itemgetter(1,3,5)('ABCDEFG')
('B', 'D', 'F')
>>> itemgetter(slice(2,None))('ABCDEFG')
'CDEFG'
>>> soldier = dict(rank='captain', name='dotterbart')
>>> itemgetter('rank')(soldier)
'captain'
使用itemgetter()从 TuplesLogging 检索特定字段的示例:
>>> inventory = [('apple', 3), ('banana', 2), ('pear', 5), ('orange', 1)]
>>> getcount = itemgetter(1)
>>> list(map(getcount, inventory))
[3, 2, 5, 1]
>>> sorted(inventory, key=getcount)
[('orange', 1), ('banana', 2), ('apple', 3), ('pear', 5)]
operator.
methodcaller
(* name ,/*, *args , * kwargs *)- 返回一个可调用对象,该对象在其操作数上调用方法* 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
将运算符 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 |
truediv(a, b) |
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) |
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) |
In-place Operators
许多操作都有“就地”版本。下面列出的函数比通常的语法提供对原始操作符的更多原始访问;例如statement x += y
等效于x = operator.iadd(x, y)
。换句话说,z = operator.iadd(x, y)
等效于复合语句z = x; z += y
。
在这些示例中,请注意,当调用就地方法时,计算和分配是在两个单独的步骤中执行的。下面列出的就地函数仅执行第一步,即调用就地方法。第二步,分配,不处理。
对于不可变的目标(例如字符串,数字和 Tuples),将计算更新后的值,但不会将其分配回 Importing 变量:
>>> a = 'hello'
>>> iadd(a, ' world')
'hello world'
>>> a
'hello'
对于诸如列表和字典之类的可变目标,就地方法将执行更新,因此不需要后续分配:
>>> s = ['h', 'e', 'l', 'l', 'o']
>>> iadd(s, [' ', 'w', 'o', 'r', 'l', 'd'])
['h', 'e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd']
>>> s
['h', 'e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd']
operator.
iadd
(* a , b *)operator.
__iadd__
(* a , b *)a = iadd(a, b)
等效于a += b
。
operator.
iand
(* a , b *)operator.
__iand__
(* a , b *)a = iand(a, b)
等效于a &= b
。
operator.
iconcat
(* a , b *)operator.
__iconcat__
(* a , b *)- 对于* a 和 b *序列,
a = iconcat(a, b)
等效于a += b
。
- 对于* a 和 b *序列,
operator.
ifloordiv
(* a , b *)operator.
__ifloordiv__
(* a , b *)a = ifloordiv(a, b)
等效于a //= b
。
operator.
ilshift
(* a , b *)operator.
__ilshift__
(* a , b *)a = ilshift(a, b)
等效于a <<= b
。
operator.
imod
(* a , b *)operator.
__imod__
(* a , b *)a = imod(a, b)
等效于a %= b
。
operator.
imul
(* a , b *)operator.
__imul__
(* a , b *)a = imul(a, b)
等效于a *= b
。
operator.
imatmul
(* a , b *)operator.
__imatmul__
(* a , b *)a = imatmul(a, b)
等效于a @= b
。
3.5 版中的新Function。
operator.
ior
(* a , b *)operator.
__ior__
(* a , b *)a = ior(a, b)
等效于a |= b
。
operator.
ipow
(* a , b *)operator.
__ipow__
(* a , b *)a = ipow(a, b)
等效于a **= b
。
operator.
irshift
(* a , b *)operator.
__irshift__
(* a , b *)a = irshift(a, b)
等效于a >>= b
。
operator.
isub
(* a , b *)operator.
__isub__
(* a , b *)a = isub(a, b)
等效于a -= b
。
operator.
itruediv
(* a , b *)operator.
__itruediv__
(* a , b *)a = itruediv(a, b)
等效于a /= b
。
operator.
ixor
(* a , b *)operator.
__ixor__
(* a , b *)a = ixor(a, b)
等效于a ^= b
。