【问题标题】:returns the location of the first item for the whole list instead of each item's location?返回整个列表的第一个项目的位置,而不是每个项目的位置?
【发布时间】:2021-09-19 19:34:43
【问题描述】:

此代码应该读取基因组的文本文件,并给定一个模式,应该返回该模式出现的次数及其位置。 相反,它只返回出现次数和第一次出现的位置。 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}")

【问题讨论】:

标签: python bioinformatics dna-sequence


【解决方案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:

【讨论】:

  • 非常感谢,它成功了。我想过返回 i 但我所做的不同它尝试了 PatternLocations.append(Text.index(i)) 但这显然给了我一个错误。
【解决方案2】:

我建议您使用re,而不是在整个文本中重复。

这是一个sn-p:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-10-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多