Reputation: 205
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!
Upvotes: 0
Views: 121
Reputation: 61930
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.
Upvotes: 2
Reputation: 92884
With collections.Counter
object to compare occurrences of respective values:
from collections import Counter
a = [1, 2, 3, 4, 4]
b = [1, 1, 2, 3, 4]
a_counts, b_counts = Counter(a), Counter(b)
res = [a_key for a_key, b_key in zip(a_counts, b_counts)
if a_counts[a_key] != b_counts[b_key]]
print(res) # [1, 4]
Upvotes: 2