我确定以前有人提出过这个问题,但我找不到确切的例子。
我有 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/