什么| =在python中意味着什么?

时间:2013-12-27 10:29:19

标签: python

|=运算符在python中意味着什么?

我在递归函数中遇到了这个|=运算符:http://nltk.googlecode.com/svn/trunk/doc/api/nltk.corpus.reader.wordnet-pysrc.html#Synset.hypernym_distances

5 个答案:

答案 0 :(得分:2)

在这种情况下,它是set运算符,用于更新集合。来自文档:

Update the set, adding elements from all others.

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

答案 1 :(得分:1)

简而言之,x |= yx = x | y的简写(虽然有些细微之处意味着这两种形式并不严格相同)。

documentation中了解详情。

在您引用的示例中,|=用于向集合添加元素。记录此用法here

  

update(other, ...)

     

set |= other | ...

     

更新集合,添加其他所有元素。

答案 2 :(得分:0)

这是一个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)

答案 3 :(得分:0)

|=的意思是Union,用于集合,

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

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

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

答案 4 :(得分:-2)

A | = B. 与以下内容相同: A = A |乙