我如何在两个水平列表之间交叉一系列列?

时间:2011-05-16 17:57:53

标签: python list intersection

在我写的代码中,我需要交叉两个水平列表,如:

listA的:

('name1','chr1', 'aatt')
('name2','chr11', 'aaga')
('name2','chr11', 'aaaa')
('name3','chr7', 'gtag')

数组listB

('chr8', 'tagt')
('chr1', 'tttt')
('chr7', 'gtag')
('chr11','aaaa')
('chr9', 'atat')

#This lists are compounded by one str per line, wich it has a "/t" in the middle. 
#Also note that are in different order

如何从listA获取第2列和第3列与listB相交的行?

期望的结果:

name2   chr11   aaaa
name3   chr7    gtag

解决方案不只是“set(listA)& set(listB)”,因为列表具有不同的列数

谢谢你的时间!

1 个答案:

答案 0 :(得分:3)

set_b = set(list_b)
result = [x for x in list_a if (x[1], x[2]) in set_b]