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

2024-09-30 04:31:58 发布

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

我正在研究生物信息学的问题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]):因此我添加了

^{pr2}$

但没关系。在

干杯


Tags: 数据脚本ifpositionrange序列listdna
3条回答

为了方便起见,我建议您使用python的regex。在

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

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

它为dna中的motif的每一次出现提供字符串中的开始索引和结束索引

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

以下是引发错误的程序:

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)):,你就会知道原因了:

^{pr2}$

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

请注意,您已经到达了行的末尾,并且它与break语句中的现有条件不匹配。在

相关问题 更多 >

    热门问题