Python:列表理解,将 2 个列表合并为 1 个具有唯一值的列表

标签 python python-3.x list-comprehension

我想创建一个列表,其中仅包含原始列表 a 中不在列表 b 中的元素。

我尝试过使用列表理解,但不明白为什么新列表中的数字重复了三次。

a = [3, 6, 7, 9, 11, 14, 15]

b = [2, 6, 7, 10, 12, 15]

c = [x for x in a if x not in b 
       for y in b if y not in a]

我期望这个结果:

[3, 9, 11, 14]

最佳答案

更简单的方法是使用集合。

set_a = set(a)
set_b = set(b)

c = list(set_a - set_b) #Using set operator difference
c.sort() #If you need to have it in order

Set Operator Difference

关于Python:列表理解,将 2 个列表合并为 1 个具有唯一值的列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58491551/

相关文章:

python - 什么是 Python 中的兄弟类?

python - 列表理解与元组赋值

python - 从字符串末尾分割字符串中的 3 个空格分隔的值?

python - 以编程方式获取和设置 QTreeview 中的事件行 (PyQt)

python - 如何使用try/except/else语法修复 “Unexpected unindent”错误

python-3.x - sklearn 与 Linux-alpine 兼容吗?

python - 用户定义的通用类型和 collections.abc

python - Pandas 切片/选择多个条件与或语句

Python 循环 vs 理解列表 vs 映射的副作用(即不使用返回值)

bash - 纯 BASH 中的列表理解?