gpt4 book ai didi

python - 搜索列表中的出现项,但仅搜索第一项

转载 作者:行者123 更新时间:2023-12-01 06:56:24 25 4
gpt4 key购买 nike

我的代码工作得很好,但我不明白为什么它只使用 searchList 形式的第一项进行搜索。这是我的代码:

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

最佳答案

第一次进入if时不能return,仅在最后返回

def analyzeSequence(dnastring, searchList):
values = {}
for item in searchList:
if dnastring.count(item) > 1:
values[item] = dnastring.index(item), dnastring.count(item)
return values

如果你有兴趣,这里是 dict 理解方式

def analyzeSequence(dna, searchList):
return {item:(dna.index(item), dna.count(item)) for item in searchList if dna.count(item)>1}

关于python - 搜索列表中的出现项,但仅搜索第一项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58790543/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com