首页 > 解决方案 > Python逻辑`and`返回错误结果比较列表

问题描述

y1 = [True, True, False, False]
y2 = [False, True, True, False]
y3 = y1 and y2

print(y3)
>>> [False, True, True, False]

这里发生了什么?操作中的第三项是FalseandTrue这会导致True?

标签: pythonboolean-logic

解决方案


X and Y评估为:

  • X(如果X的)
  • Y(如果X真的

任何非空列表都是真实的。

因此,如果

y1 = [True, True, False, False]

y2 = [False, True, True, False]

然后y1 and y2计算为y2,即[False, True, True, False]

如果您想要列表中and的单个元素,您可以使用zip列表理解

y3 = [x1 and x2 for x1,x2 in zip(y1,y2)]

推荐阅读