从python中的两个列表中删除交集

Nat*_*ath -2 python

给出两个列表,删除两者交集的最佳方法是什么?例如,给定:

a = [2,2,2,3]
b = [2,2,5]
Run Code Online (Sandbox Code Playgroud)

我想回来:

a = [2,3]
b = [5]
Run Code Online (Sandbox Code Playgroud)

ran*_*mir 8

假设您希望处理一般情况(相同的元素在每个列表中出现多次),即所谓的multiset.

你可以使用collections.Counter:

from collections import Counter
intersection = Counter(a) & Counter(b)
multiset_a_without_common = Counter(a) - intersection
multiset_b_without_common = Counter(b) - intersection
new_a = list(multiset_a_without_common.elements())
new_b = list(multiset_b_without_common.elements())
Run Code Online (Sandbox Code Playgroud)

为了您的价值观a,b你会得到:

a = [2,2,2,3]
b = [2,2,5]
new_a = [2, 3]
new_b = [5]
Run Code Online (Sandbox Code Playgroud)

请注意,对于每个元素只出现一次的特殊情况,您可以使用标准set,正如其他答案所暗示的那样.