数组列表索引超出范围

2024-09-24 22:26:28 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个155大小的数组,我的程序包括你输入一个单词,然后在数组中搜索这个单词。 但是当我输入'176'这是数组中的最后一个单词时,它会给出一个list 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

Tags: andof程序index错误range数组out
2条回答

你的索引超出了界限。以下是列表索引的工作方式:

>>> 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超出范围,可能是因为您正在一个list/iterable(resList)中获取一个索引,并将其用作另一个/较小的list/iterable(resultss)的索引。

这是预期的行为。如果有listlenx,则x索引未定义。

例如:

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

相关问题 更多 >