循环时所有项目都不附加

时间:2016-03-24 06:54:27

标签: list python-3.x

def PatternMatching(Pattern, Genome):
    positions = [] # output variable    
    for i in range(len(Genome)-len(Pattern)+1):    
        if Genome[i:i+len(Pattern)] == Pattern:
            print(i, Pattern)
            positions.append(Genome.index(Pattern))    
    return positions
# Now, set Text equal to the oriC of Vibrio cholerae and Pattern equal to "TGATCA"
Pattern = "TGATCA"
Genome="ATCAATGATCAACGTAAGCTTCTAAGCATGATCAAGGTGCTCACACAGTTTATCCACAACCTGAGTGGATGACATCAAGATAGGTCGTTGTATCTCCTTCCTCTCGTACTCTCATGACCACGGAAAGATGATCAAGAGAGGATGATTTCTTGGCCATATCGCAATGAATACTTGTGACTTGTGCTTCCAATTGACATCTTCAGCGCCATATTGCGCTGGCCAAGGTGACGGAGCGGGATTACGAAAGCATGATCATGGCTGTTGTTCTGTTTATCTTGTTTTGACTGAGACTTGTTAGGATAGACGGTTTTTCATCACTGACTAGCCAAAGCCTTACTCTGCCTGACATCGACCGTAAATTGATAATGAATTTACATGCTTCCGCGACGATTTACCTCTTGATCATCGATCCGATTGAAGATCTTCAATTGTTAATTCTCTTGCCTCGACTCATAGCCATGATGAGCTCTTGATCATGTTTCCTTAACCCTCTATTTTTTACGGAAGAATGATCAAGCTGCTGCTCTTGATCATCGTTTC"    

print(PatternMatching(Pattern, Genome))

此函数仅返回[5,5,5,5,5,5,5,5],但正确的输出将是[5,28,128,249,399,470,509,527]

为什么首先匹配索引为所有后续匹配返回?

1 个答案:

答案 0 :(得分:0)

我在代码中发现了我的错误。行position.append(Genome.index(Pattern))应替换为positions.append(i)。这给出了正确的结果。