Home > Back-end >  Python - Intersection of multiple lists taken two at a time
Python - Intersection of multiple lists taken two at a time

Time:11-24

In python, I am able to get intersection of multiple lists:

arr = [[1, 2, 3], [2, 3, 4], [3, 4, 5]]
result = set.intersection(*map(set, arr))

Output:

result = {3}

Now, I want the result as intersection of all 3 nested lists taken 2 at a time:

result = {2, 3, 4}

as [2, 3] is common between 1st and 2nd lists, [3, 4] is common between 2nd and 3rd lists and [3] is common between 1st and 3rd lists.

Is there a built in function for this?

CodePudding user response:

Try itertools.combinations

from itertools import combinations
arr = [[1, 2, 3], [2, 3, 4], [3, 4, 5]]
result = [set.intersection(*map(set, i)) for i in combinations(arr,2)] 
# print(list(combinations(arr,2)) to get the combinations
# [{2, 3}, {3}, {3, 4}]

CodePudding user response:

You can take a union of the all pairs of intersections as follows;

import itertools as it
arr = [[1, 2, 3], [2, 3, 4], [3, 4, 5]]
res = set.union(*(set(i).intersection(set(j)) for i,j in it.pairwise(arr)))
# output {2, 3, 4}
  • Related