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

ard*_*igh 4 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]
Run Code Online (Sandbox Code Playgroud)

编辑 基于所做的评论,此代码不满足仅添加一次,即:

>>> 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]
Run Code Online (Sandbox Code Playgroud)

我怎么会最终得到:

[1, 2, 3, 4]
Run Code Online (Sandbox Code Playgroud)

the*_*eye 5

如果您想维护订单,可以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]
Run Code Online (Sandbox Code Playgroud)

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

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

  • `list(OrderedDict.fromkeys(chain(list1,list2)))`将在Python 2.x和Python 3.x中工作. (2认同)