繁体   English   中英

数组列表索引超出范围

[英]array list index out of range

我有一个155的数组,我的程序包括你输入一个单词,然后在数组中搜索单词。 但是当我输入'176'这是数组中的最后一个单词时,它会给出一个list index out of rangelist index out of range错误为什么会这样?

i = resList.index(resiID) # --searchs list and give number where found, for last word gives 155
print len(resultss) # --prints 155
colour = resultss[i] # --error given on this line

这是预期的行为。 如果您有一个lenxlist ,那么x索引是未定义的。

例如:

lst = [0,1]
print len(lst) # 2
print lst[0] # 0
print lst[1] # 1
print lst[len(lst)] #error

你的索引超出范围。 以下是列表索引的工作方式:

>>> a = list(range(10))
>>> a
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> i = a.index(9)
>>> i
9
>>> a[i]
9
>>> a[10]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
IndexError: list index out of range

如果索引的长度为i ,则可以使用0..i-1范围内的任何索引。 最后一个有效索引是len(mylist) - 1

155超出范围,也许是因为你是在一个列表/迭代(获得索引resList ),并用它作为索引到一个不同的/较小目录/迭代( resultss )。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM