[英]While-loop - IndexError: list assignment index out of range
I keep getting Index Errors when I try to use while loops in combination with lists. 当我尝试结合列表使用while循环时,我不断收到索引错误。
I wrote the code some time ago, came back to it, but just couldn't wrap my head around it enough to find my mistake. 我前一段时间写了代码,又回到了上面,但是只是无法将其包裹在头以找到我的错误。 Apparently, the error has something to do with my lists indexes being too small or too large.
显然,该错误与我的列表索引太小或太大有关。
indexes = []
#Or indexes[0], but this threw another error
indexes.append(decoded.find(special_string))
x=1
while indexes[x-1] > 0:
total = sum(indexes)
indexes[x] = decoded.find(special_string, total)
x+=1
print(indexes)
My goal is to find all substrings (special_string) in a string and get their indexes (please inform me if you know an easier way to do this). 我的目标是找到字符串中的所有子字符串(special_string)并获取它们的索引(如果您知道更简单的方法,请通知我)。 I want to write all indexes out into a list for further use.
我想将所有索引写到列表中以备将来使用。
I think the only change you need to make is from: 我认为您需要进行的唯一更改是来自:
indexes[x] = decoded.find(special_string, total)
to: indexes[x] = decoded.find(special_string, total)
为:
indexes.append(decoded.find(special_string, total))
You can't assign indexes[x] since it doesn't exist. 您不能分配索引[x],因为它不存在。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.