gpt4 book ai didi

python - 为什么我的零列表会导致 IndexError?

转载 作者:行者123 更新时间:2023-12-03 08:19:33 27 4
gpt4 key购买 nike

我在 occurence[j] = 0 上收到错误消息.我真的不明白我的代码中这个错误的起源,因为它的长度是 dna,因为我在代码的顶部附加了 len(dna)零,然后我将一些值分配给同一个列表 occurence在我的嵌套循环中,j只能达到len(dna)的值.

for i in range(len(dna)):
occurence.append(0)

print(f"{len(dna)}")
print(f"{len(occurence)}")

#Calculating consecutive sequences and creating a 2D array occurence...
for i in types:
for j in range(len(dna)):
if (dna[j:j+len(i)] != i):
occurence[j] = 0
else:

space = len(i)

while(dna.find(i, space+len(i)) != -1):
index = dna.find(i, space+len(i))
space = space + len(i)
if (index == len(i)):
occurence[j] += 1

for k in range(len(occurence)):
maximum = 0
if(occurence[k] > maximum):
maximum = occurence[k]
counts.append(maximum)
maximum = 0
occurence.clear()

最佳答案

在第一次迭代结束时 types ,您调用occurence.clear() ,这将导致 occurence是一个空列表。然后,当您尝试访问 occurence[j]在第二次迭代中,这会抛出 IndexError因为列表是空的。

我认为你想在 for i in types 中初始化你的列表。循环,例如:

for i in types:
occurence = [0] * len(dna)
for j in range(len(dna)):
...

这样您就不需要调用 clear列表中的方法,因为它会在每次迭代中被重新定义为一个零列表。

关于python - 为什么我的零列表会导致 IndexError?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60902584/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com