为什么 `True and ~True` -2?

Why is `True and ~True` -2?

如果这是 below-standard 问题,我非常抱歉,但我找不到明确的答案。

正如标题所说,为什么True and (~True)给出-2而True&(~True)给出0? 另外,为什么他们两个都不给False

这非常 counter-intuitive,因为我希望单个布尔表达式 &and 应该以相同的方式工作。

True 在 Python 中的值为 1。位反转 (~) 二进制 1 (...0001) 给你 ...1110。由于负整数由 two's compliment 表示,因此值为 -2。

逻辑 and returns 如果为假则为左操作数,否则为右操作数。 (显然,True 永远不会为假。)

另一方面,

按位 & 适用于各个位。 ...0001 & ...1110 在同一位置没有 1 位,因此它们在结果中都是零。


I was just surprised that a numpy array with dtype=bool acts differently with literal bool

每个 Python 类型都可以实现具有特殊方法名称的运算符方法。 (比如 .__invert__() 代表 ~)。但是 andornot 没有这些钩子,因此通常使用 &|~ 代替。对于 ints,实现是按位的,但其他类型可以根据需要解释运算符。

注意 bool 是 Python 中 int 的子类,因此它与 int 具有相同的运算符。但是您是在 numpy.ndarray 上操作,而不是在其各个组件上操作,因此 Python 使用运算符的 ndarray 实现,这与 bool 不同 dtype=bool.

记住,True == 1False == 0

所以,

True and (~True)

相同
1 and (~1)

~ is a bitwise operation。哪种反转1的二进制。如果我们

print(~1)

-2

所以整个事情被简化为

1 and -2

Which is just -2


& 对比 and

I expect for a single boolean expression & and and should in the same way

不要! and 是一个布尔测试。 & 是位运算。两者都非常不同。