Python 如何获取两个列表并将它们组合起来排除任何重复项?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4674013/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 16:52:17  来源:igfitidea点击:

How to take two lists and combine them excluding any duplicates?

python

提问by funk-shun

I'd like to make one list from two separate lists of unique items.

我想从两个单独的独特项目列表中列出一个列表。

There are other similar questions but there didn't seem to be any that concerned doing this problem effectively since the lists are a few million items long.

还有其他类似的问题,但似乎没有任何人关心有效地解决这个问题,因为列表有几百万个项目。

Totally unrelated: am I the only one who hates how the tags suggestion box covers up the "post your question" button?

完全无关:我是唯一一个讨厌标签建议框如何掩盖“发布您的问题”按钮的人吗?

采纳答案by user225312

Use a set.

使用一个set.

>>> first = [1, 2, 3, 4]
>>> second = [3, 2, 5, 6, 7]
>>> third = list(set(first) | set(second))      # '|' is union
>>> third
[1, 2, 3, 4, 5, 6, 7]

回答by virhilo

>>> l1 = range(10)
>>> l2 = range(5, 15)
>>> set(l1) | set(l2)
set([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14])

回答by Prashant Lakhera

If someone want to do it without set():

如果有人不想这样做set()

a = [1,2,3]
b = [2,3,4]
newlist=[]
for i in a:
    newlist.append(i)
for z in b:
    if z not in newlist:
        newlist.append(z)
newlist.sort()
print newlist

回答by Benjamin Devienne

A slightly more efficient way to do it:

一种稍微更有效的方法:

>>> first = [1, 2, 3, 4]
>>> second = [3, 2, 5, 6, 7]

# New way
>>> list(set(first + second))
[1, 2, 3, 4, 5, 6, 7]
#1000000 loops, best of 3: 1.42 μs per loop

# Old way
>>> list(set(first) | set(second))
[1, 2, 3, 4, 5, 6, 7]
#1000000 loops, best of 3: 1.83 μs per loop

The new way is more efficient because it has only one set() instead of 2.

新方法更有效,因为它只有一个 set() 而不是 2。