Skip to main content
 首页 » 编程设计

python之在两组同步列表中查找匹配项

2025年05月04日16telwanggs

我有两组同步的列表,如下所示: (同步我的意思是cal中的'A'在cpos中属于12,而mal中的'A'在mpos中属于11)

第一组

cpos = [12, 13, 14, 15] 
cal = ['A', 'T', 'C', 'G'] 

第二组

mpos = [11, 12, 13, 16] 
mal = ['A', 'T', 'T', 'G'] 

我想找到两个集合之间的匹配项,在这个例子中只有一个匹配项,cpos&cal 中的 13T 和 mpos&mal 中的 13T。

我写了这个脚本,但它似乎只是按索引比较值,因为匹配字符串是空的:

mat = [] 
for i in xrange(len(cpos)): 
     if mpos[i] == cpos[i] and mal[i] == cal[i]: 
             mat.append(cpos[i]) 

这是我想要得到的:

mat = [13] 

有什么解决办法吗?

请您参考如下方法:

cpos = [12, 13, 14, 15] 
cal = ['A', 'T', 'C', 'G'] 
 
mpos = [11, 12, 13, 16] 
mal = ['A', 'T', 'T', 'G'] 
 
set1 = set(zip(cpos, cal)) 
set2 = set(zip(mpos, mal)) 
 
print set1 & set2 

结果:

## set([(13, 'T')]) 

根据@Janne Karila 在下面的评论,以下内容会更有效率:

from itertools import izip 
print set(izip(cpos, cal)).intersection(izip(mpos, mal)) 

时间:

import timeit 
 
repeat = 1 
 
setup = ''' 
num = 1000000 
import random 
import string 
from itertools import izip 
cpos = [random.randint(1, 100) for x in range(num)] 
cal = [random.choice(string.letters) for x in range(num)] 
mpos = [random.randint(1, 100) for x in range(num)] 
mal = [random.choice(string.letters) for x in range(num)] 
''' 
 
# izip: 0.38 seconds (Python 2.7.2) 
t = timeit.Timer( 
     setup = setup, 
     stmt = '''set(izip(cpos, cal)).intersection(izip(mpos, mal))''' 
) 
 
print "%.2f second" % (t.timeit(number=repeat)) 
 
 
 
# zip: 0.53 seconds (Python 2.7.2) 
t = timeit.Timer( 
     setup = setup, 
     stmt = '''set(zip(cpos, cal)) & set(zip(mpos, mal))''' 
) 
 
print "%.2f second" % (t.timeit(number=repeat)) 
 
 
# Nested loop: 616 seconds (Python 2.7.2) 
t = timeit.Timer( 
     setup = setup, 
     stmt = ''' 
 
mat = [] 
for i in xrange(len(cpos)): 
     for j in xrange(len(mpos)): 
          if mpos[j] == cpos[i] and mal[j] == cal[i]: 
               mat.append(mpos[j]) # or mat.append((mpos[j], mal[j])) ? 
               break 
''' 
) 
 
print "%.2f seconds" % (t.timeit(number=repeat))