从元组列表中获取交集 [英] Get intersection from list of tuples
问题描述
我有两个元组列表
a = [('head1','a'),('head2','b'),('head3','x'),('head4','z')]
b = [('head5','u'),('head6','w'),('head7','x'),('head8','y'),('head9','z')]
我想使用每个元组的第二个元素的交集,例如set {a[0][0],a[0][1],a[0][2],a[0][3]}
与列表a
和b
中的set {b[0][0],b[0][1],b[0][2],b[0][3],b[0][4]}
的交集,以便如果交集值返回元组的第一个元素映射存在.结果输出应如下所示:
I want to take the intersection of 2nd element of each tuple for example set {a[0][0],a[0][1],a[0][2],a[0][3]}
intersection with set {b[0][0],b[0][1],b[0][2],b[0][3],b[0][4]}
from list a
and b
such that it returns the first element mapping of the tuple if intersection value exist. The resulting output should be like following:
res = [('head3','head7'),('head4','head9')]
到目前为止,我已经尝试过:
So far I have tried this:
x = [(a[i][0],b[j][0]) for i in range(len(a)) for j in range(len(b)) if a[0][i] == b[0][j]]
但出现错误IndexError: tuple index out of range
这样做的正确,最快的方法是什么?
What could be the correct and fastest way of doing this ?
推荐答案
您可以在Python 3中执行以下操作.从列表中创建字典,并从两个字典中获取键的交集,然后从键中获取相应的值:
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')]
在Python 2中,可以使用set(da).intersection(db)
代替da.keys()&db.keys()
.
In Python 2, you can use set(da).intersection(db)
in place of da.keys()&db.keys()
.
这篇关于从元组列表中获取交集的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!