且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

合并两个列表并删除重复项,而不删除原始列表中的重复项

更新时间:2023-02-22 12:34:37

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

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))