python - 尝试在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]
解决方案
如前所述:两个布尔列表上的 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])
返回False
while a==3 is false
And
a=2
print(a==2 and [1,1,0,0])
返回[1,1,0,0]
时a==2 is true
推荐阅读
- python - tf.keras.preprocessing.image_dataset_from_directory 没有从目录中读取所有图像,而只是其中的一部分
- html - 在 Blazor 中返回字符串
- python - 多次更新 shapefile 中的数据
- common-lisp - 在符号列表上调用 print-object
- jquery - 如何选择任何类型(文本、单选、复选框)的所有输入元素?
- c++ - 我可以按值重新排序地图中的元素吗?C++
- ruby-on-rails - 在 UI 模式下在 Github 操作中运行 Capybara 测试
- r - 将字符串作为文字传递以创建图形对象
- c# - ASP.NET Core MVC 修改实体导致 NullReferenceException
- android - 如何在android的edittext中使第一个字符为数字,第二个字符为字母?