Pipe character in Python

I see a "pipe" character (|) used in a function call:

res = c1.create(go, come, swim, "", startTime, endTime, "OK", ax|bx)

What is the meaning of the pipe in ax|bx?

99395 次浏览

It is a 按位 OR of integers. For example, if one or both of ax or bx are 1, this evaluates to 1, otherwise to 0. It also works on other integers, for example 15 | 128 = 143, i.e. 00001111 | 10000000 = 10001111 in binary.

它是位或者。

Python 中所有运算符的文档可以在 Python 文档的 索引-符号页中找到。

This is also the union set operator

set([1,2]) | set([2,3])

这将导致 set([1, 2, 3])

是的,以上所有答案都是正确的。

尽管您可以找到更多关于“ |”的特殊用例,例如,如果它是一个由类使用的重载运算符,

Https://github.com/twitter/pycascading/wiki#pycascading

input = flow.source(Hfs(TextLine(), 'input_file.txt'))
output = flow.sink(Hfs(TextDelimited(), 'output_folder'))


input | map_replace(split_words, 'word') | group_by('word', native.count()) | output

In this specific use case pipe "|" operator can be better thought as a unix pipe operator. But I agree, bit-wise operator and union set operator are much more common use cases for "|" in Python.

在标题为 规格的部分的 Python 3.9-PEP 584-添加联合运算符中,解释了操作符。 对管道进行了增强,以合并(联合)字典。

>>> d = {'spam': 1, 'eggs': 2, 'cheese': 3}
>>> e = {'cheese': 4, 'nut': 5}
>>> d | e
{'spam': 1, 'eggs': 2, 'cheese': 4, 'nut': 5} # comment 1
>>> e | d
{'cheese': 3, 'nut': 5, 'spam': 1, 'eggs': 2} # comment 2

comment 1 If a key appears in both operands, the last-seen value (i.e. that from the right-hand operand) wins --> 'cheese': 4 instead of 'cheese': 3

注释2 Cheese 出现两次,所以选择第二个值 d[cheese]=3