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

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

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

>>> [0,0,1,1,0] or [1,1,0,1,0]
[0, 0, 1, 1, 0]

我想要的结果是

[1,1,1,1,0]

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

python comparison
2个回答
1
投票

您可以使用

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]

1
投票

使用numpy:


import numpy as np

np.logical_or([0,0,1,1,0], [1,1,0,1,0]).astype(int)
array([1, 1, 1, 1, 0])

并检查这个问题的答案:

Python 布尔值比较列表给出奇怪的结果

© www.soinside.com 2019 - 2024. All rights reserved.