Triath
Triath

Reputation: 31

How to take intersection of 2 or more lists that includes tuples?

I want to compare tuples in two or more lists and print out the intersection of them. I have 25 element (which includes empty) in every tuple and tuple count changes in every list.

So far I have tried taking intersection of two lists, the code that I used can be seen below :

res_final = set(tuple(x) for x in res).intersection(set(tuple(x) for x in res1))

output:

set()

(res and res1 are my lists)

Upvotes: 0

Views: 83

Answers (2)

logc
logc

Reputation: 3923

If your input looks something like this:

in_1 = [(1, 1), (2, 2), (3, 3)]
in_2 = [(4, 4), (5, 5), (1, 1)]
in_3 = [(6, 6), (7, 7), (1, 1)]
ins = [in_1, in_2, in_3]

then I think you can use itertools.combinations to find pairwise intersections, and then take a set from them in order to remove duplicates.

from itertools import combinations

intersected = []
for first, second in combinations(ins, 2):
    elems = set(first).intersection(set(second))
    intersected.extend(elems)

dedup_intersected = set(intersected)
print(dedup_intersected)
# {(1, 1)}

Upvotes: 0

silgon
silgon

Reputation: 7221

Hope this example helps:

import numpy as np
np.random.seed(0)  # random seed for repeatability
a_ = np.random.randint(15,size=(1000,2))  # create random data for tuples
b_ = np.random.randint(15,size=(1000,2))  # create random data for tuples
a, b = set(tuple(d) for d in a_), set(tuple(d) for d in b_)  # set of tuples
intersection = a&b  # intersection
print(intersection)  # result

In the code, matrices of random variables are created, then the rows are converted to tuples. Then we get the set of tuples and finally the important part for you, the intersection of the tuples.

Upvotes: 1

Related Questions