逻辑与按位运算符AND [英] Logical vs. bitwise operator AND
本文介绍了逻辑与按位运算符AND的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
即使我读到其他一些关于它的问题,我也不理解&
和 and
之间的区别.
I don’t understand the difference between &
and and
, even if I read some other questions about it.
我的代码是:
f=1
x=1
f==1 & x==1
Out[60]: True
f==1 and x==1
Out[61]: True
f=1
x=2
f==1 and x==2
Out[64]: True
f==1 & x==2
Out[65]: False
为什么是第二个&
False
,而第一个是 True
?
Why is it the second &
False
, whereas the first is True
?
推荐答案
问题是&
的运算符优先级高于 ==
.
The issue is that &
has higher operator precedence than ==
.
>>> (f == 1) & (x == 2)
True
>>> f == (1 & x) == 2
False
也许这似乎是不直观的,但是&
实际上是要在数字之间用于特定类型的计算:
Perhaps this seems unintuitive, but &
is really meant to be used between numbers for particular kinds of calculations:
>>> 3 & 5
1
因此它与 +
和 *
之类的运算符具有相似的优先级,明智的做法是应在 ==
之前对它们进行评估.完全不打算将其与和
相似地使用.
so it has similar precedence to operators like +
and *
, which sensibly should be evaluated before ==
. It's not meant to be used in a similar manner to and
at all.
这篇关于逻辑与按位运算符AND的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文