python - Get intersection from list of tuples -


i have 2 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 take intersection of 2nd element of each tuple example set {a[0][0],a[0][1],a[0][2],a[0][3]} intersection set {b[0][0],b[0][1],b[0][2],b[0][3],b[0][4]} list a , b such returns first element mapping of tuple if intersection value exist. resulting output should following:

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

so far have tried this:

x = [(a[i][0],b[j][0]) in range(len(a)) j in range(len(b)) if a[0][i] == b[0][j]] 

but got error indexerror: tuple index out of range

what correct , fastest way of doing ?

you can following in python 3. create dicts lists, taking intersection of keys both dicts, fetch corresponding values @ key:

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

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


Comments

Popular posts from this blog

node.js - Node js - Trying to send POST request, but it is not loading javascript content -

javascript - Replicate keyboard event with html button -

javascript - Web audio api 5.1 surround example not working in firefox -