根据我对按位运算符的理解,下面的代码应该只在 i 和 j 都等于 5 时执行,对于 i 和 j 的所有其他值,如果条件应评估为 False。但我得到以下输出:
for i in range(30):
for j in range(30):
if i == 5 & j == 5:
print(i, j, i & j, bin(i==5), bin(j==5), i == 5 & j == 5)
输出:
# i, j, i & j, binary value of i, binary value of j, bitwise and of i == 5 and j == 5
5 5 5 0b1 0b1 True
5 7 5 0b1 0b0 False
5 13 5 0b1 0b0 False
5 15 5 0b1 0b0 False
5 21 5 0b1 0b0 False
5 23 5 0b1 0b0 False
5 29 5 0b1 0b0 False
问题:
i 和 j 的二进制值仅在第一种情况下为 1,那为什么其他情况都被打印?
为什么在 i 和 j 计算为 5 的地方打印结果
如果我改变上面 if 语句中的条件顺序,i 获取值 5、7、13、15、21、23、29,而 j 保持为 5,其他输出也相同。为什么?
对于上面的代码,i = 7 和 j = 5,i & j 的计算结果也为 5。那为什么不打印呢?
请您参考如下方法:
Unlike C, all comparison operations in Python have the same priority, which is lower than that of any arithmetic, shifting or bitwise operation. Also unlike C, expressions like a < b < c have the interpretation that is conventional in mathematics:
所以在这里:
i == 5 & j == 5
发生的事情是 5 & j 针对 i 和 5 进行相等性测试。所以括号是可行的,但正确的方法是使用 logical and 运算符,它具有更高的优先级:
i == 5 and j == 5
它还会短路,这意味着如果i != 5,甚至不会测试j(执行速度更快)。完全适用于此示例。
