首页 > 解决方案 > 尝试在python中按位和两个列表

问题描述

我在 python shell 中做了以下操作。第一个和第三个输出是正确的,但第二个输出是错误的。我知道我可以使用 zip 函数来做到这一点,但我想知道为什么 python 会这样做。

>>> [1,1,1,1] and [1,0,0,0]
[1, 0, 0, 0]
>>> [1,0,0,0] and [1,1,0,0]
[1, 1, 0, 0]
>>> [1,1,1,1] and [0,0,0,0]
[0, 0, 0, 0]

标签: pythoncommand-linedata-sciencepython-3.7

解决方案


如前所述:两个布尔列表上的 Python AND 运算符 - 怎么样?
“并且根据它们的真值简单地返回第一个或第二个操作数。如果第一个操作数被认为是假的,则返回它,否则返回另一个操作数。” 马丁·彼得斯

[1,1,1,1] and [1,0,0,0]
=> [1, 0, 0, 0] which is second operand while first is true.

另一个例子:

a=2
print(a==3 and [1,1,0,0])

返回Falsewhile a==3 is false
And

a=2
print(a==2 and [1,1,0,0])

返回[1,1,0,0]a==2 is true


推荐阅读