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

2024-05-12 19:30:33 发布

您现在位置:Python中文网/ 问答频道 /正文

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

集合1

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

集合2

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]

有什么办法解决这个问题吗?你知道吗


Tags: 字符串in脚本列表forlenif例子
3条回答

现在只按索引进行比较,即只在所有列表中的i位置进行比较。但cpos&cal中的13T位于1位置,mpos&mal中的13T位于2位置。这意味着if语句将不为true,mat将为空。你知道吗

您可以在示例中添加第二个循环:

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

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

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])) ?

print mat # [13]

..尽管这是非常低效的,如thg435答案中的计时所示

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))

相关问题 更多 >