搜索列表引用,但仅搜索第一项

2024-10-01 19:17:41 发布

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

我的代码工作得不错,但我不明白为什么它只使用第一项表单搜索列表进行搜索。这是我的代码:

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

Tags: 代码表单newcountpositionitemgcseq
1条回答
网友
1楼 · 发布于 2024-10-01 19:17:41

您不能在第一次进入returnif,只能在最后返回

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}

相关问题 更多 >

    热门问题