Search code examples
pythonmultiset

find the non intersection between 2 list, including duplicate


I tried to look up this question before asking but could not find any satisfactory. so I have 2 list like this

a=[1,2,3,4,4]
b=[1,1,2,3,4]

I tried this:

set(a) - set(b)

but got this

set()

what I want is this

[1,4]

Since set a has 2 4s and set b has 2 1s. What can I do? Thank you!


Solution

  • Use collections.Counter, is the Python implementation of a multiset:

    from collections import Counter
    
    a = [1, 2, 3, 4, 4]
    b = [1, 1, 2, 3, 4]
    c = [1, 1, 1, 2, 3, 4]
    
    counts_a = Counter(a)
    counts_b = Counter(b)
    counts_c = Counter(c)
    
    result_b = (counts_a | counts_b) - (counts_a & counts_b)
    result_c = (counts_a | counts_c) - (counts_a & counts_c)
    
    print(list(result_b.elements()))
    print(list(result_c.elements()))
    

    Output

    [1, 4]
    [1, 1, 4]
    

    Note that (counts_a | counts_b) - (counts_a & counts_b) is the Python equivalent of the mathematical formula.