在字符串中查找字符串的实例

Finding a instances of a string inside a string

我正在 rosalind.org 上解决生物信息学问题,我遇到了一个问题,我编写的 python 脚本适用于较小的数据集,但应用于较大的数据集时第一,我收到 IndexError: list index out of range 消息。

基本上我有一个较小的基序和一个较大的 DNA 序列,我必须在 DNA 序列中找到基序的实例。当我将问题中的示例数据集放入我的脚本时,它工作正常并且我得到了正确的答案。然而,使用明显更大的图案和序列会产生前面提到的错误。

这是我的代码:

motif = "<motif around 9 characters>"
cMotif = list(motif)
motifLength = len(cMotif)

dna = "<DNA sequence around 900 characters>"
dnArray = list(dna)

locations = ""

position = 0

for nt in dnArray:
        if (nt == cMotif[0]):
                for x in range(0, (motifLength)):
                        if ((x + position) > len(dnArray)):
                                break

                        if (dnArray[position + x] == cMotif[x]):
                                if (x >= (motifLength - 1)):
                                        locations += (str(position + 1) + "      ")
                                       break 
                        else:
                                break
        position += 1

print(locations)

第 18 行出现 IndexError: list index out of range 错误,if (dnArray[position + x] == cMotif[x]): 因此我添加了

if ((x + position) > len(dnArray)):
                                    break

但这没有什么不同。

干杯

Python 的列表是从零开始的,因此当 (x + position) == len(dnArray) 尝试访问 dnArray[x + position] 时,将是最后一个索引之后的一个。您应该将测试更改为 if (x + position) >= len(dnArray): 以解决您的问题。

为了简单起见,我建议您使用 python 的正则表达式。

import re
motif = "abc"
dna = "helloabcheyabckjlkjsabckjetc"

for i in re.finditer(motif,dna):
    print(i.start(), i.end())

它为您提供 dna

中每次出现 motif 的开始和结束索引

这是你的程序抛出错误:

motif = "abcd"
cMotif = list(motif)
motifLength = len(cMotif)

dna = "I am a dna which has abcd in it.a"
dnArray = list(dna)

locations = ""

position = 0

for nt in dnArray:
        if (nt == cMotif[0]):
                for x in range(0, (motifLength)):
                        if ((x + position) > len(dnArray)):
                                break

                        if (dnArray[position + x] == cMotif[x]):
                                if (x >= (motifLength - 1)):
                                    locations += (str(position + 1) + "      ")
                                    break 
                        else:
                                break
        position += 1

print(locations)

我将 if ((x + position) > len(dnArray)): 更改为 if ((x + position) >= len(dnArray)): 并且错误消失了,因为您的程序永远不会进入 break 语句,因为您没有检查 "=" 条件.请记住,在编程语言中,事物从 0 开始。

把这条线放在你的条件上面if ((x + position) > len(dnArray)):你就知道原因了:

print("My position is: " + str(x+position) + " and the length is: " + str(len(dnArray)))

此打印语句的最后一行将指示 My position is: 33 and the length is: 33

看到这里你已经到了行尾,它不符合你现有的条件,不能进入 break 语句。