gpt4 book ai didi

python - 有没有一种Python式的方法来迭代两个列表的差异?

转载 作者:行者123 更新时间:2023-12-03 01:07:04 25 4
gpt4 key购买 nike

我的目标是迭代两个列表的差异

我尝试使用 bodge 代码编写 a - b 如下

for i in a:
if i in b:
continue
#statements

我想知道是否有一种更Pythonic/更有效的方法来做到这一点。

最佳答案

您可以使用sets ,看看差异:

a = [1, 2, 3, 4, 5]
b = [2, 4, 6]

a = set(a)
b = set(b)

for i in a.difference(b):
print(i)

# even supports the arithmetic syntax :D
for i in a - b:
print(i)

关于python - 有没有一种Python式的方法来迭代两个列表的差异?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58223932/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com