返回整个列表的第一个项目的位置而不是每个项目的位置?

时间:2021-07-09 12:27:20

标签: python bioinformatics dna-sequence

这段代码应该读取一个基因组的文本文件,并给出一个模式,应该返回模式出现的次数及其位置。 相反,它仅返回出现次数和第一次出现的位置。 this is an example of running the code 不是返回 35 次出现的位置,而是返回第一个位置 35 次。

# open the file with the original sequence
myfile = open('Vibrio_cholerae.txt')

# set the file to the variable Text to read and scan
Text = myfile.read()

# insert the pattern
Pattern = "TAATGGCT"

PatternLocations = []

def PatternCount(Text,Pattern):
    count = 0
    for i in range (len(Text)-len(Pattern)+1):
        if Text [i:i+len(Pattern)] == Pattern:
            count +=1
            PatternLocations.append(Text.index(Pattern))
    return count


# print the result of calling PatternCount on Text and Pattern.
print (f"Number of times the Pattern is repeated: {PatternCount(Text,Pattern)} time(s).")
print(f"List of Pattern locations: {PatternLocations}")

2 个答案:

答案 0 :(得分:1)

你做到了

PatternLocations.append(Text.index(Pattern))

.index 带单个参数确实

Return the lowest index in S where substring sub is found

你应该这样做

PatternLocations.append(i)

因为您自己找到位置而不使用索引而是使用

if Text [i:i+len(Pattern)] == Pattern:

答案 1 :(得分:0)

我建议您使用 re,而不是通篇重复。

这是一个片段:

from re import finditer
for match in finditer(pattern, Text):
    print(match.span(), match.group())

从我使用的自定义示例 (pattern='livraison') 中,它返回如下内容:

>>>(18, 27) livraison
>>>(80, 89) livraison
>>>(168, 177) livraison
>>>(290, 299) livraison