谷歌不让我搜索|=,所以我很难找到相关的文件。有人知道吗?
当前回答
当与set一起使用时,它执行联合操作。
其他回答
这只是当前变量和另一个变量之间的OR运算。当T=True和F=False时,请以图形方式查看输出:
r | s | r|=s |
---|---|---|
T | T | T |
T | F | T |
F | T | T |
F | F | F |
例如:
>>> r=True
>>> r|=False
>>> r
True
>>> r=False
>>> r|=False
>>> r
False
>>> r|=True
>>> r
True
它表示按位或操作。
例子:
x = 5
x |= 3 #which is similar to x = x | 3
print(x)
答案:7
它是如何工作的?
The binary of 5 is : 0 1 0 1
The binary of 3 is : 0 0 1 1
OR operation : (If one of both sides are 1/True then result is 1/True)
0 1 0 1 #Binary of 5
0 0 1 1 #Binary of 3
---------------------
0 1 1 1 #Binary of 7
所以答案是7
|是位或。所以x |= y等价于x = x | y。
对于集合,|有一个相关的含义:集合并集。与你在数学中使用OR求两个集合的交集相同,你可以在python中使用|
*注意:这两个表达式不是100%等效的。在x |= y后,id(x) == id(y)。x = x | y后,id(x) != id(y)
在Python中,|=(ior)类似于联合运算。 例如,如果x=5和x|=5,那么两个值都将首先转换为二进制值,然后执行并集操作,我们得到答案5。
给出一个用例(在花时间分析其他答案之后):
def process(item):
return bool(item) # imagine some sort of complex processing taking place above
def any_success(data): # return True if at least one is successful
at_least_one = False
for item in data:
at_least_one |= process(item)
return at_least_one
>>> any_success([False, False, False])
False
>>> any_success([True, False, False])
True
>>> any_success([False, True, False])
True
基本上没有短路:如果你需要处理每个项目并记录至少一次成功,可能会有用。
请参见此回答中的注意事项
推荐文章
- 证书验证失败:无法获得本地颁发者证书
- 当使用pip3安装包时,“Python中的ssl模块不可用”
- 无法切换Python与pyenv
- Python if not == vs if !=
- 如何从scikit-learn决策树中提取决策规则?
- 为什么在Mac OS X v10.9 (Mavericks)的终端中apt-get功能不起作用?
- 将旋转的xtick标签与各自的xtick对齐
- 为什么元组可以包含可变项?
- 如何合并字典的字典?
- 如何创建类属性?
- 不区分大小写的“in”
- 在Python中获取迭代器中的元素个数
- 解析日期字符串并更改格式
- 使用try和。Python中的if
- 如何在Python中获得所有直接子目录