列表上的 Python boolean 运算 - 不一致的结果

标签 python list boolean operator-keyword

假设我有两个列表:

>>> y
[False, False, True, False, True, False, False, True, False, True, False, False]
>>> z
[False, True, True, True, True, True, False, False, False, False, False, True]

然后我执行以下操作:

>>> y or z
[False, False, True, False, True, False, False, True, False, True, False, False]
>>> z or y
[False, True, True, True, True, True, False, False, False, False, False, True]

正确答案不应该如下图所示吗?

[False, True, True, True, True, True, False, True, False, True, False, True]

我也得到了 的错误答案:

>>> y and z
[False, True, True, True, True, True, False, False, False, False, False, True]
>>> z and y
[False, False, True, False, True, False, False, True, False, True, False, False]

我用奇怪的结果测试了 1 和 0:

>>> y=[0,0,0,0,0]
>>> z=[1,1,1,1,1]
>>> y or z
[0, 0, 0, 0, 0]
>>> z or y
[1, 1, 1, 1, 1]
>>> y and z
[1, 1, 1, 1, 1]
>>> z and y
[0, 0, 0, 0, 0]

我做错了什么?

最佳答案

y 或 z 在单个元素上的行为与您想象的不同。相反,它评估第一个参数 (y) 的“真实性”。由于 y 是一个非空列表,因此它的计算结果为 true。然后整个语句的计算结果为 y

类似地,z 或 y 首先查看 z 是否为真(确实如此,因为它是一个非空列表)。因此,该语句的计算结果为 z,而无需查看 y 或其中的元素。

这里有一些更清楚的例子:

>>> [1,2,3,4] or [5,6,7,8]
[1, 2, 3, 4]
>>> ['this','is','a','list'] or ['and','here','is','another']
['this', 'is', 'a', 'list']

空列表的计算结果为“false-y”,因此在这种情况下,右侧列表是语句的值:

>>> [] or ['and','here','is','another']
['and', 'here', 'is', 'another']

交换列表的顺序表明第一个评估为真的将是结果:

>>> ['and','here','is','another'] or ['this','is','a','list']
['and', 'here', 'is', 'another']

为了实现你想要的,你可以像这样做一个列表理解

[
    y_item or z_item
    for y_item, z_item
    in zip(y, z)
]

关于列表上的 Python boolean 运算 - 不一致的结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43719498/

相关文章:

python - 在 Python 中,我如何使用列表理解来遍历列表列表?

python - "__requires__"在 python 中是什么意思?

jquery - 是否有一个 jquery List 插件可以自动排序项目并具有强大的添加/删除方法?

sql - 将数据帧添加到 Spark 中的列表

c++ - 双重比较

r - 在嵌套 ifelse 中正确使用 "IS NOT" "OR"和 "AND" boolean 值

python - str.format 以 dict 作为参数引发 KeyError

python - 如何在 python 中从一个 .py 文件运行多个 .py 文件

list - 如何从列表中发出每个项目之间有延迟的项目?

带整数的 C++ boolean 值