【问题标题】:While-loop - IndexError: list assignment index out of rangeWhile-loop - IndexError:列表分配索引超出范围
【发布时间】:2019-06-18 00:09:03
【问题描述】:

当我尝试将 while 循环与列表结合使用时,我不断收到索引错误。

我前段时间编写了代码,后来又回来了,但是我无法完全理解它以找出我的错误。显然,该错误与我的列表索引太小或太大有关。

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)

我的目标是找到字符串中的所有子字符串(special_string)并获取它们的索引(如果您知道更简单的方法,请告诉我)。我想将所有索引写到一个列表中以供进一步使用。

【问题讨论】:

  • 我想将 index[1] 声明为 decoded.find(node_identifier, total) 以便它忽略第一个 special_string 并给我下一个的位置。
  • 你为什么要对索引求和?此外,这种方法总是会导致列表索引超出范围,因为您尝试索引列表而不检查其大小。
  • 我试图总结一下,以便知道我已经迭代了多少个字符。

标签: python list index-error


【解决方案1】:

我认为你需要做的唯一改变是:

indexes[x] = decoded.find(special_string, total) 到:

indexes.append(decoded.find(special_string, total))

您不能分配索引[x],因为它不存在。

【讨论】:

  • 感谢您的回答!我会尽快接受的。
猜你喜欢
  • 2020-09-17
  • 1970-01-01
  • 2020-02-03
  • 2018-10-21
  • 2020-02-13
  • 1970-01-01
  • 2019-03-28
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多