假设我有两个列表:
>>> 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/