合并两个列表并删除重复项,而不删除原始列表中的重复项 [英] Combining two lists and removing duplicates, without removing duplicates in original list

查看:79
本文介绍了合并两个列表并删除重复项,而不删除原始列表中的重复项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个列表需要合并,第二个列表忽略了第一个列表的重复项. ..有点难以解释,所以让我展示一个示例,说明代码的外观以及结果.

I have two lists that i need to combine where the second list has any duplicates of the first list ignored. .. A bit hard to explain, so let me show an example of what the code looks like, and what i want as a result.

first_list = [1, 2, 2, 5]

second_list = [2, 5, 7, 9]

# The result of combining the two lists should result in this list:
resulting_list = [1, 2, 2, 5, 7, 9]

您会注意到结果具有第一个列表,包括其两个"2"值,但是second_list也具有附加的2和5值的事实并未添加到第一个列表中

You'll notice that the result has the first list, including its two "2" values, but the fact that second_list also has an additional 2 and 5 value is not added to the first list.

通常对于类似这样的事情,我会使用集合,但是first_list上的集合会清除它已经具有的重复值.因此,我只是想知道哪种最佳/最快的方法来实现所需的组合.

Normally for something like this i would use sets, but a set on first_list would purge the duplicate values it already has. So i'm simply wondering what the best/fastest way to achieve this desired combination.

谢谢.

推荐答案

您需要将第二个列表中不在第一个列表中的元素添加到第一个列表中-套是确定它们属于哪些元素的最简单方法,就像这样:

You need to append to the first list those elements of the second list that aren't in the first - sets are the easiest way of determining which elements they are, like this:

first_list = [1, 2, 2, 5]
second_list = [2, 5, 7, 9]

in_first = set(first_list)
in_second = set(second_list)

in_second_but_not_in_first = in_second - in_first

result = first_list + list(in_second_but_not_in_first)
print result  # Prints [1, 2, 2, 5, 9, 7]

或者,如果您希望使用8层一线纸

Or if you prefer one-liners 8-)

print first_list + list(set(second_list) - set(first_list))

这篇关于合并两个列表并删除重复项,而不删除原始列表中的重复项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆