Skip to content Skip to sidebar Skip to footer

Get Intersection From List Of Tuples

I have two list of tuples a = [('head1','a'),('head2','b'),('head3','x'),('head4','z')] b = [('head5','u'),('head6','w'),('head7','x'),('head8','y'),('head9','z')] I want to take

Solution 1:

You can do the following in Python 3. Create dicts from your lists, taking the intersection of keys from both dicts, fetch the corresponding values at the key:

>>> da = {k:v for v, k in a}
>>> db = {k:v for v, k in b}
>>> [(da[k], db[k])  for k in da.keys()&db.keys()]
[('head4', 'head9'), ('head3', 'head7')]

In Python 2, you can use set(da).intersection(db) in place of da.keys()&db.keys().

Solution 2:

You can use a function with a generator:

def pairs():
   a = [('head1','a'),('head2','b'),('head3','x'),('head4','z')]
   b = [('head5','u'),('head6','w'),('head7','x'),('head8','y'),('head9','z')]

   for val1, val2 in a:
       for val3, val4 in b:
           if val2 == val4:
               yield (val1, val3)

print(list(pairs()))

Output:

[('head3', 'head7'), ('head4', 'head9')]

Solution 3:

You can also use a list comprehension like this

a = [('head1','a'),('head2','b'),('head3','x'),('head4','z')]
b = [('head5','u'),('head6','w'),('head7','x'),('head8','y'),('head9','z')]

pairs = [(val1,val3) for val1,val2 in a for val3,val4 in b if val2 == val4]
print(pairs)

Post a Comment for "Get Intersection From List Of Tuples"