在Python中,|=表示按位或赋值运算符。

3
5个回答

6
在这种情况下,它是一个“set”运算符,用于更新集合。参考文档如下:

Update the set, adding elements from all others.

来源:http://docs.python.org/2/library/stdtypes.html#set.update

这个函数会将集合的内容更新为两个或更多集合的并集。与 union() 相比,update() 原地修改了调用集合,而不是创建一个新的集合来存储结果。


3
有趣的是,这里的文档有误。在一个 set 对象上调用 .update() 方法并不会返回任何内容,它会直接就地修改这个 set 对象。 - Tim Pietzcker
4
内置类型set的文档是正确的,只有旧的已弃用的sets模块的文档是错误的。 - Bakuriu
2
顺便提一下,这个答案链接到了错误的文档。 - user2357112
@Bakuriu:确实,我甚至没有注意到这不是内置文档。 - Tim Pietzcker
@TimPietzcker 谢谢,已修复! - Fabian

4
简而言之,x |= yx = x | y的简写(尽管存在细微差别,导致这两种形式并非完全等价)。
文档中可以了解更多信息。
在你引用的示例中,|=用于向集合中添加元素。此用法在此处有文档说明:

update(other, ...)

set |= other | ...

更新集合,将所有其他集合中的元素添加到该集合中。


3
我想知道是谁浏览并对除了一个回答以外的所有回答点了踩。这里没有什么值得被点踩的东西。 - user2357112
@user2357112,和我的回答一样 :/ - Dunno

2
这是Python内置的交互式帮助(help()函数)的打印输出,非常有用!
help> |=

Augmented assignment statements
*******************************

Augmented assignment is the combination, in a single statement, of a
binary operation and an assignment statement:

   augmented_assignment_stmt ::= augtarget augop (expression_list | yield_expression)
   augtarget                 ::= identifier | attributeref | subscription | slicing
   augop                     ::= "+=" | "-=" | "*=" | "/=" | "//=" | "%=" | "**="
             | ">>=" | "<<=" | "&=" | "^=" | "|="

(See section *Primaries* for the syntax definitions for the last three
symbols.)

An augmented assignment evaluates the target (which, unlike normal
assignment statements, cannot be an unpacking) and the expression
list, performs the binary operation specific to the type of assignment
on the two operands, and assigns the result to the original target.
The target is only evaluated once.
An augmented assignment expression like ``x += 1`` can be rewritten as
``x = x + 1`` to achieve a similar, but not exactly equal effect. In
the augmented version, ``x`` is only evaluated once. Also, when
possible, the actual operation is performed *in-place*, meaning that
rather than creating a new object and assigning that to the target,
the old object is modified instead.

With the exception of assigning to tuples and multiple targets in a
single statement, the assignment done by augmented assignment
statements is handled the same way as normal assignments. Similarly,
with the exception of the possible *in-place* behavior, the binary
operation performed by augmented assignment is the same as the normal
binary operations.

For targets which are attribute references, the same *caveat about
class and instance attributes* applies as for regular assignments.
(END)

1

|= 在集合中表示 并集

s1 = set([4,3,7])
s2 = set([0,2,1])
s1 |= s3

>> {0, 1, 3, 4, 7}

由于集合的特性(仅包含唯一项),结果包含唯一值。


-1

A |= B 与以下等式相同: A = A | B


这不正确。|= 调用 __ior__,如果可能的话会改变 A 的值,而 | 调用 __or__= 会将 A 重新绑定到新对象的结果上。 - Tim Pietzcker
我明白了,这是一个坑!(感谢及时纠正!) - user3127145

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接