谷歌不让我搜索|=,所以我很难找到相关的文件。有人知道吗?
当前回答
给出一个用例(在花时间分析其他答案之后):
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
基本上没有短路:如果你需要处理每个项目并记录至少一次成功,可能会有用。
请参见此回答中的注意事项
其他回答
它是位或。 假设我们有32 | 10,图片32和10的二进制:
32 = 10 0000
10 = 00 1010
现在,因为|是“或”运算,对这两个数字进行“或”运算
即1或0——> 1 0或0——> 0。沿着这个链条继续下去:
10 0000 | 00 1010 = 10 1010.
现在把二进制变成十进制,10 1010 = 42。
对于|=,考虑已知的例子,x +=5。这意味着x = x + 5,因此如果我们有x |= 5,这意味着x = x位或5。
它对赋值的左侧和右侧执行二进制位或运算,然后将结果存储在左侧变量中。
http://docs.python.org/reference/expressions.html#binary-bitwise-operations
它表示按位或操作。
例子:
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)
当与set一起使用时,它执行联合操作。
推荐文章
- 证书验证失败:无法获得本地颁发者证书
- 当使用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中获得所有直接子目录