Python 搜索列表引用,但仅搜索第一项
我的代码工作得不错,但我不明白为什么它只使用第一项表单搜索列表进行搜索。这是我的代码:Python 搜索列表引用,但仅搜索第一项,python,Python,我的代码工作得不错,但我不明白为什么它只使用第一项表单搜索列表进行搜索。这是我的代码: def analyzeSequence(dnastring,searchList): empty = {} for item in searchList: if dnastring.count(item) > 1: position = dnastring.index(item) times = dnastring.coun
def analyzeSequence(dnastring,searchList):
empty = {}
for item in searchList:
if dnastring.count(item) > 1:
position = dnastring.index(item)
times = dnastring.count(item)
new = position, times
empty[item] = new
return empty
seq = "ATGCGATGCTCATCTGCATGCTGA"
sList = ["CAT","GC"]
print(analyzeSequence(seq,sList))
它打印:
{'CAT': (10, 2)}
但我想把它打印出来:
{'CAT': (10, 2), 'GC': (2, 4)}
您不能在第一次进入
时返回,如果
,请仅在末尾返回
def analyzeSequence(dnastring, searchList):
values = {}
for item in searchList:
if dnastring.count(item) > 1:
values[item] = dnastring.index(item), dnastring.count(item)
return values
如果你感兴趣,这里是听写理解的方法
def analyzeSequence(dna, searchList):
return {item:(dna.index(item), dna.count(item)) for item in searchList if dna.count(item)>1}
此字典中不可能有多个值,因为在将值放入字典后,会立即返回该字典。我建议将return empty
行取消插入for
循环之外。