Question

I'm newbie on Python. I have this list:

a = [[0,1,2,3],[4,5,6,7,8,9], ...]
b = [[0,6,9],[1,5], ...]

a & b can have more components, depends on data. I want to know is there any intersection on these lists? If there's any intersection, I wanna have a result like this:

c = [[6,9], ...]
Was it helpful?

Solution 2

Given that intersection is an operation between two sets, and you have given two lists of lists, it's very unclear what you're looking for. Do you want the intersection of a[1] and b[0]? Do you want the intersection of every possible combination?

I'm guessing you want the intersection of every combination of two sets between your two lists, which would be:

from itertools import product
[set(x).intersection(set(y)) for x, y in product(a, b)]

OTHER TIPS

The set type, built into Python, supports intersection natively. However, note that set can only hold one of each element (like a mathematical set). If you want to hold more than one of each element, try collections.Counter.

You can make sets using {} notation (like dictionaries, but without values):

>>> a = {1, 2, 3, 4, 5}
>>> b = {2, 4, 6, 8, 10}

and you can intersect them using the & operator:

>>> print a & b
set([2, 4])

First of all, in your example code this is not a tuple, it's a list (the original question asked about lists, but references tuples in the example code).

To get an intersection of two tuples or lists, use a code like this:

set((1,2,3,4,5)).intersection(set((1,2,3,7,8)))

In one line:

common_set = set([e for r in a for e in r])&set([e for r in b for e in r])

Or easier:

common_set = set(sum(a,[])) & set(sum(b,[]))

Common will be a set. You can easily convert set to the list is you need it:

common_list = list(common_set)

Another way to do it... assuming you want the intersection of the flatten list.

>>> from itertools import chain

>>> a = [[0,1,2,3],[4,5,6,7,8,9]]
>>> b = [[0,6,9],[1,5]]

>>> list(set(chain(*a)).intersection(set(chain(*b))))
[0, 9, 5, 6, 1]
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top