operatorStandard operators as functions标准运算符作为函数

Source code: Lib/operator.py


The operator module exports a set of efficient functions corresponding to the intrinsic operators of Python. For example, operator.add(x, y) is equivalent to the expression x+y. operator模块导出一组与Python的内部运算符相对应的有效函数。例如,运算符operator.add(x, y)等价于表达式x+yMany function names are those used for special methods, without the double underscores. 许多函数名用于特殊方法,没有双下划线。For backward compatibility, many of these have a variant with the double underscores kept. 为了向后兼容,其中许多具有保留双下划线的变体。The variants without the double underscores are preferred for clarity.为清晰起见,首选不带双下划线的变体。

The functions fall into categories that perform object comparisons, logical operations, mathematical operations and sequence operations.这些函数分为执行对象比较、逻辑运算、数学运算和序列运算的类别。

The object comparison functions are useful for all objects, and are named after the rich comparison operators they support:对象比较函数对所有对象都很有用,并以其支持的丰富比较运算符命名:

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)

Perform “rich comparisons” between a and b. ab之间进行“丰富的比较”。Specifically, lt(a, b) is equivalent to a < b, le(a, b) is equivalent to a <= b, eq(a, b) is equivalent to a == b, ne(a, b) is equivalent to a != b, gt(a, b) is equivalent to a > b and ge(a, b) is equivalent to a >= b. 具体来说,lt(a, b)等于a < ble(a, b)等于a<=beq(a, b)等于a==bne(a, b)等于a != bgt(a, b)等于a>bge(a, b)等于a>=bNote that these functions can return any value, which may or may not be interpretable as a Boolean value. 请注意,这些函数可以返回任何值,这些值可以解释为布尔值,也可以不解释为布尔值。See Comparisons for more information about rich comparisons.有关丰富比较的更多信息,请参阅比较

The logical operations are also generally applicable to all objects, and support truth tests, identity tests, and boolean operations:逻辑运算通常也适用于所有对象,并支持真值测试、身份测试和布尔运算:

operator.not_(obj)
operator.__not__(obj)

Return the outcome of not obj. 返回not obj的结果。(Note that there is no __not__() method for object instances; only the interpreter core defines this operation. (注意,对象实例没有__not__()方法;只有解释器核心定义此操作。The result is affected by the __bool__() and __len__() methods.)结果受__bool__()__len__()方法的影响。)

operator.truth(obj)

Return True if obj is true, and False otherwise. 如果objTrue,则返回True,否则返回FalseThis is equivalent to using the bool constructor.这相当于使用bool构造函数。

operator.is_(a, b)

Return a is b. 返回a is bTests object identity.测试对象标识。

operator.is_not(a, b)

Return a is not b. 返回a is not bTests object identity.测试对象标识。

The mathematical and bitwise operations are the most numerous:数学运算和位运算最多:

operator.abs(obj)
operator.__abs__(obj)

Return the absolute value of obj.返回obj的绝对值。

operator.add(a, b)
operator.__add__(a, b)

Return a + b, for a and b numbers.对于ab数字,返回a + b

operator.and_(a, b)
operator.__and__(a, b)

Return the bitwise and of a and b.返回ab的按位与。

operator.floordiv(a, b)
operator.__floordiv__(a, b)

Return a // b.返回a // b

operator.index(a)
operator.__index__(a)

Return a converted to an integer. 返回a转换为整数。Equivalent to a.__index__().相当于a.__index__()

Changed in version 3.10:版本3.10中更改: The result always has exact type int. 结果总是具有精确的int类型。Previously, the result could have been an instance of a subclass of int.以前,结果可能是int的一个子类的实例。

operator.inv(obj)
operator.invert(obj)
operator.__inv__(obj)
operator.__invert__(obj)

Return the bitwise inverse of the number obj. 返回数字obj的位逆。This is equivalent to ~obj.这相当于~obj

operator.lshift(a, b)
operator.__lshift__(a, b)

Return a shifted left by b.返回a左移b

operator.mod(a, b)
operator.__mod__(a, b)

Return a % b.返回a % b

operator.mul(a, b)
operator.__mul__(a, b)

Return a * b, for a and b numbers.对于ab数字,返回a*b

operator.matmul(a, b)
operator.__matmul__(a, b)

Return a @ b.

New in version 3.5.版本3.5中新增。

operator.neg(obj)
operator.__neg__(obj)

Return obj negated (-obj).返回obj否定(-obj)。

operator.or_(a, b)
operator.__or__(a, b)

Return the bitwise or of a and b.返回ab的按位或。

operator.pos(obj)
operator.__pos__(obj)

Return obj positive (+obj).返回obj正极(+obj)。

operator.pow(a, b)
operator.__pow__(a, b)

Return a ** b, for a and b numbers.对于ab数字,返回a**b

operator.rshift(a, b)
operator.__rshift__(a, b)

Return a shifted right by b.返回右移ba

operator.sub(a, b)
operator.__sub__(a, b)

Return a - b.返回a - b

operator.truediv(a, b)
operator.__truediv__(a, b)

Return a / b where 2/3 is .66 rather than 0. 返回a/b,其中2/3为.66而不是0。This is also known as “true” division.这也称为“真实”分割。

operator.xor(a, b)
operator.__xor__(a, b)

Return the bitwise exclusive or of a and b.返回ab的位异或。

Operations which work with sequences (some of them with mappings too) include:处理序列的操作(其中一些也处理映射)包括:

operator.concat(a, b)
operator.__concat__(a, b)

Return a + b for a and b sequences.返回ab序列的a+b

operator.contains(a, b)
operator.__contains__(a, b)

Return the outcome of the test b in a. 返回b in a测试的结果。Note the reversed operands.请注意反转的操作数。

operator.countOf(a, b)

Return the number of occurrences of b in a.返回ab的出现次数。

operator.delitem(a, b)
operator.__delitem__(a, b)

Remove the value of a at index b.删除索引b处的a值。

operator.getitem(a, b)
operator.__getitem__(a, b)

Return the value of a at index b.返回索引ba的值。

operator.indexOf(a, b)

Return the index of the first of occurrence of b in a.返回ab第一次出现的索引。

operator.setitem(a, b, c)
operator.__setitem__(a, b, c)

Set the value of a at index b to c.将索引b处的a值设置为c

operator.length_hint(obj, default=0)

Return an estimated length for the object o. 返回对象o的估计长度。First try to return its actual length, then an estimate using object.__length_hint__(), and finally return the default value.首先尝试返回其实际长度,然后使用object.__length_hint__()进行估计,最后返回默认值。

New in version 3.4.版本3.4中新增。

The operator module also defines tools for generalized attribute and item lookups. operator模块还定义了用于通用属性和项查找的工具。These are useful for making fast field extractors as arguments for map(), sorted(), itertools.groupby(), or other functions that expect a function argument.这些对于将快速字段提取器作为map()sorted()itertools.groupby()或其他需要函数参数的函数的参数非常有用。

operator.attrgetter(attr)
operator.attrgetter(*attrs)

Return a callable object that fetches attr from its operand. 返回一个可调用对象,该对象从其操作数中获取attrIf more than one attribute is requested, returns a tuple of attributes. 如果请求了多个属性,则返回属性元组。The attribute names can also contain dots. 属性名称也可以包含点。For example:例如:

  • After f = attrgetter('name'), the call f(b) returns b.name.f = attrgetter('name')之后,调用f(b)返回b.name

  • After f = attrgetter('name', 'date'), the call f(b) returns (b.name, b.date).f = attrgetter('name', 'date')之后,调用f(b)返回(b.name, b.date)

  • After f = attrgetter('name.first', 'name.last'), the call f(b) returns (b.name.first, b.name.last).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(*items)

Return a callable object that fetches item from its operand using the operand’s __getitem__() method. 返回一个可调用的对象,该对象使用操作数的__getitem__()方法从其操作数中获取itemIf multiple items are specified, returns a tuple of lookup values. 如果指定了多个项,则返回查找值的元组。For example:例如:

  • After f = itemgetter(2), the call f(r) returns r[2].f = itemgetter(2)之后,调用f(r)返回r[2]

  • After g = itemgetter(2, 5, 3), the call g(r) returns (r[2], r[5], r[3]).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

The items can be any type accepted by the operand’s __getitem__() method. 这些项可以是操作数的__getitem__()方法接受的任何类型。Dictionaries accept any hashable value. 字典接受任何可散列值。Lists, tuples, and strings accept an index or a slice:列表、元组和字符串接受索引或切片:

>>> 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'

Example of using itemgetter() to retrieve specific fields from a tuple record:使用itemgetter()从元组记录中检索特定字段的示例:

>>> 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)

Return a callable object that calls the method name on its operand. 返回一个可调用对象,该对象调用其操作数上的方法nameIf additional arguments and/or keyword arguments are given, they will be given to the method as well. 如果提供了其他参数和/或关键字参数,则它们也将提供给该方法。For example:例如:

  • After f = methodcaller('name'), the call f(b) returns b.name().f = methodcaller('name')之后,调用f(b)返回b.name()

  • After f = methodcaller('name', 'foo', bar=1), the call f(b) returns b.name('foo', bar=1).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

Mapping Operators to Functions将运算符映射到函数

This table shows how abstract operations correspond to operator symbols in the Python syntax and the functions in the operator module.此表显示了抽象操作如何对应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)

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)

In-place Operators就地运算符

Many operations have an “in-place” version. Listed below are functions providing a more primitive access to in-place operators than the usual syntax does; for example, the statement x += y is equivalent to x = operator.iadd(x, y). 许多操作都有“就地”版本。下面列出的函数提供了比通常语法更原始的就地运算符访问;例如,语句x += y相当于x = operator.iadd(x, y)Another way to put it is to say that z = operator.iadd(x, y) is equivalent to the compound statement z = x; z += y.另一种说法是,z = operator.iadd(x, y)等价于复合语句z = x; z += y

In those examples, note that when an in-place method is called, the computation and assignment are performed in two separate steps. 在这些示例中,请注意,当调用就地方法时,计算和赋值分两个单独的步骤执行。The in-place functions listed below only do the first step, calling the in-place method. 下面列出的就地函数只执行第一步,即调用就地方法。The second step, assignment, is not handled.第二步,分配,没有处理。

For immutable targets such as strings, numbers, and tuples, the updated value is computed, but not assigned back to the input variable:对于字符串、数字和元组等不可变目标,会计算更新后的值,但不会将其分配回输入变量:

>>> a = 'hello'
>>> iadd(a, ' world')
'hello world'
>>> a
'hello'

For mutable targets such as lists and dictionaries, the in-place method will perform the update, so no subsequent assignment is necessary:对于列表和字典等可变目标,就地方法将执行更新,因此无需后续赋值:

>>> 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) is equivalent to a += b.等于a+=b

operator.iand(a, b)
operator.__iand__(a, b)

a = iand(a, b) is equivalent to a &= b.等于a &= b

operator.iconcat(a, b)
operator.__iconcat__(a, b)

a = iconcat(a, b) is equivalent to a += b for a and b sequences.对于ab序列,等价于a += b

operator.ifloordiv(a, b)
operator.__ifloordiv__(a, b)

a = ifloordiv(a, b) is equivalent to a //= b.等于a//=b

operator.ilshift(a, b)
operator.__ilshift__(a, b)

a = ilshift(a, b) is equivalent to a <<= b.等于a <<= b

operator.imod(a, b)
operator.__imod__(a, b)

a = imod(a, b) is equivalent to a %= b.等于a %= b

operator.imul(a, b)
operator.__imul__(a, b)

a = imul(a, b) is equivalent to a *= b.等于a *= b

operator.imatmul(a, b)
operator.__imatmul__(a, b)

a = imatmul(a, b) is equivalent to a @= b.等于@=b

New in version 3.5.版本3.5中新增。

operator.ior(a, b)
operator.__ior__(a, b)

a = ior(a, b) is equivalent to a |= b.等于a |= b

operator.ipow(a, b)
operator.__ipow__(a, b)

a = ipow(a, b) is equivalent to a **= b.等于a **= b

operator.irshift(a, b)
operator.__irshift__(a, b)

a = irshift(a, b) is equivalent to a >>= b.等于a>>=b

operator.isub(a, b)
operator.__isub__(a, b)

a = isub(a, b) is equivalent to a -= b.等于a-=b

operator.itruediv(a, b)
operator.__itruediv__(a, b)

a = itruediv(a, b) is equivalent to a /= b.等于a/=b

operator.ixor(a, b)
operator.__ixor__(a, b)

a = ixor(a, b) is equivalent to a ^= b.等于a ^=b