IndexError:列表索引超出范围错误。 (蟒蛇)

时间:2014-11-30 03:37:23

标签: python python-2.7

当我提交以下代码时:

data = open("DNA Motif.txt", "r")
lines = data.readlines()
large = list(lines[0])
small = list(lines[1])
list = []
counts = []

print large

for first in range(0, len(large)):
    list = []
    if large[first] == small[0]:
        for other in range(0, len(small)):
            if small[other] == large[first + other]:
                list.append(large[first + other])
            if list == small:
                counts.append(str(first + 1))

使用以下数据集:

TTGCGTTTCGCGTTTCTCCGTTGCGTTTCTAGCGTTTCCAGGCGACCGCGTTTCGCGTTTCAGCGTTTCGCGTTTCGCGTTTCGCGTTTCCCCGGGGGCGTTTCGCGTTTCGGCGTTTCCAGCGTTTCCGCGTTTCGCGTTTCGCGTTTCAGCATAGTTAGCGTTTCATCGCGTTTCGCGTTTCTTTTATGCTGTTGCGTTTCTGCTTAGGCGTTTCTACACTCAGCGTTTCGCGTTTCAGCGTTTCAGCGTTTCACAGCGTTTCGCGTTTCTGGCGTTTCGCCGCGTTTCCCGTGCGTTTCATTCTTGCGTTTCTGCGTTTCTCGAGAGCGTTTCGCGTTTCGTACGCGTTTCGCGTTTCTTAAGAGCGTTTCCGCGTTTCGTTACGCGTTGCAAGCGTTTCGGCGTTTCTCAGGCGTTTCGTGCGTTTCTGCGTTTCGCGTTTCTTTGCGTTTCGCGTTTCGAAAGCGTTTCGGTTGCCTACGTATATACTTGCGTTTCGCGTTTCCTTCTAAAGGCGTTTCATAGCGTTTCGCCCTGGAGCGTTTCCGGAGAGCGTTTCTGCGTTTCAGCGTTTCTGCGTTTCAGGAGCGTTTCGGTGAGATTTAGCGTTTCCTATCGGCGTTTCTGGCGTTTCCTCGAAAGCGTTTCAGGCGTTTCATGCGTTTCTGCGTTTCGCGTTTCTCCGGCGTTTCGGCGTTTCGGCGTTTCGCGTTTCAGCGTTTCCAGCGTTTCAAGCGGCGTTTCACGCGTTTCGCGTTTCGCGTTTCGCGTTTCACTGCGTTTCAAGCGTTTCGCGTTTCGCGTTTCAACGCTGCGTTTCAGCGTTTCGCGTTTCGCGTTTCTGACCCGCGTTTCAGCGTTTCTGGGATAGCGTTTCGTGCGTTTCGCGTTTCGCGGTGACGCGTTTC
GCGTTTCGC

我收到此错误:

IndexError: list index out of range

如果你能提供帮助那就太好了。我理解错误是什么,以及我应该如何解决它,但我不知道具体在我的代码中修复了什么。

1 个答案:

答案 0 :(得分:0)

for first in range(0, len(large)):                       #1
    list = []
    if large[first] == small[0]:
        for other in range(0, len(small)):               #2
            if small[other] == large[first + other]:     #3
  1. 最大值firstlen(large) - 1

  2. 最大值otherlen(small) - 1

  3. 因此,first + other的最大值为len(large) + len(small) - 2

  4. 鉴于您的示例输入中的len(small)为9,first + other在某些时候显然会大于len(large),但您仍尝试将其用作一个大的索引。

    您需要修复逻辑 - 或者,如Martijn Pieters pointed out,使用更简单的方法。