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

标签 python python-3.x list

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

我尝试使用 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/

相关文章:

python - 找不到域 'django' 的翻译文件

根据两组有效条目检查列表端点的pythonic方法

Mac OSX 中的 Python 启动器首选项不允许选择 python 3.6 解释器

python - Lambda 过滤字典列表 Python

Python 列表说明 : Assigning values directly is not possible

python - 与 numpy 并行初始化矩阵

python - 如何在Python中访问模块级名称?

python-3.x - docker : Opensearch refuses connection with the example in opensearch documentation in docker

python-3.x - 如何使用 pandas python 对特定列进行操作第 3 部分

Python:如何将具有多个数字的多个列表转换为数组?