python - 有条件地附加列表的最佳 Pythonic 方式

标签 python list-comprehension

我确定以前有人提出过这个问题,但我找不到确切的例子。

我有 2 个列表,想将第二个附加到第一个,只有其中的值不存在。

到目前为止我有工作代码,但想知道是否有更好、更“Pythonic”的代码:

>>> list1
[1, 2, 3]
>>> list2
[2, 4]
>>> list1.extend([x for x in list2 if x not in list1])
>>> list1
[1, 2, 3, 4]

编辑 根据评论,此代码不满足仅添加一次,即:

>>> list1 = [1,2,3]
>>> list2 = [2,4,4,4]
>>> list1.extend([x for x in list2 if x not in list1])
>>> list1
[1, 2, 3, 4, 4, 4]

我将如何结束:

[1, 2, 3, 4]

最佳答案

如果要维护顺序,可以使用collections.OrderedDict像这样

from collections import OrderedDict
from itertools import chain
list1, list2 = [1, 2, 3], [2, 4]
print list(OrderedDict.fromkeys(chain(list1, list2)))
# [1, 2, 3, 4]

如果元素的顺序不重要,你可以像这样使用set

from itertools import chain
list1, list2 = [1, 2, 3], [2, 4]
print list(set(chain(list1, list2)))
# [1, 2, 3, 4]

关于python - 有条件地附加列表的最佳 Pythonic 方式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22226239/

相关文章:

python - 从 Excel 多表文件 : List comprehension between columns 解析

python - 从 python 中的一行中拉出特定的子字符串

python - 如何通过 SqlAlchemy 中的 joinloaded 表进行过滤?

python - 如何区分 lambda 和 def 函数?

python - 如何从 Qtable 获取值

python - 如何更快地从列表中删除包含某些单词的字符串

python - 列表理解拆分循环变量

python - 在 python 中爬取社交网络

python - 在 Python 的类方法中创建实例

python - 组合两个或多个具有相同键的字典