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

时间:2017-06-24 22:17:52

标签: python

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

a = [2,2,2,3]
b = [2,2,5]

我想回来:

a = [2,3]
b = [5]

3 个答案:

答案 0 :(得分:7)

假设您希望处理一般情况(每个列表中相同的元素出现多次),即所谓的 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())

对于ab的值,您将获得:

a = [2,2,2,3]
b = [2,2,5]
new_a = [2, 3]
new_b = [5]

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

答案 1 :(得分:1)

您可以遍历两个列表并在找到交叉点时删除元素,如下所示:

a = [2, 2, 2, 3]
b = [2, 2, 5]
delete = []
for c in a:
    for n in b:
        if n == c:
            delete.append(c)
            delete.append(n)
            break
    a.remove(delete[0])
    b.remove(delete[1])
    delete = []
print a
print b

输出:

[2, 3]
[5]

答案 2 :(得分:0)

a = [2,2,2,3]
b = [2,2,5]
for i in list(b): #I call list() on b because otherwise I can't remove from it during the for loop.
    if i in a:
        a.remove(i)
        b.remove(i)

输出:

a = [2, 3]
b = [5]