I know how to get an intersection of two flat lists:
b1 = [1,2,3,4,5,9,11,15]
b2 = [4,5,6,7,8]
b3 = [val for val in b1 if val in b2]
or
<
Use this method if repetition matters
from collections import Counter
def intersection(a, b):
"""
Find the intersection of two iterables
>>> intersection((1,2,3), (2,3,4))
(2, 3)
>>> intersection((1,2,3,3), (2,3,3,4))
(2, 3, 3)
>>> intersection((1,2,3,3), (2,3,4,4))
(2, 3)
>>> intersection((1,2,3,3), (2,3,4,4))
(2, 3)
"""
return tuple(n for n, count in (Counter(a) & Counter(b)).items() for _ in range(count))
def difference(a, b):
"""
Find the symmetric difference of two iterables
>>> difference((1,2,3), (2,3,4))
(1, 4)
>>> difference((1,2,3,3), (2,3,4))
(1, 3, 4)
>>> difference((1,2,3,3), (2,3,4,4))
(1, 3, 4, 4)
"""
diff = lambda x, y: tuple(n for n, count in (Counter(x) - Counter(y)).items() for _ in range(count))
return diff(a, b) + diff(b, a)