使用 OR 比较两个列表的元素

问题描述 投票:0回答:1

我想用 OR 比较两个相同长度的列表的元素。

但是如果我在提示中输入

 [0,0,1,1,0] or [1,1,0,1,0]
,我会得到
[0, 0, 1, 1, 0]
.

但我希望结果是

[1,1,1,1,0]

如何才能达到想要的比较效果?

python comparison
1个回答
0
投票

您可以使用

zip()
函数同时迭代两个列表的相应元素,然后使用列表推导式对每对元素执行
OR
操作。

list1 = [0, 0, 1, 1, 0]
list2 = [1, 1, 0, 1, 0]

result = [a or b for a, b in zip(list1, list2)]
print(result)

输出:

[1, 1, 1, 1, 0]
© www.soinside.com 2019 - 2024. All rights reserved.