数组列表索引超出范围
我有一个大小为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
2 个回答
3
这是正常的情况。如果你有一个 list
(列表),它的长度是 x
,那么 x
这个位置是没有定义的。
举个例子:
lst = [0,1]
print len(lst) # 2
print lst[0] # 0
print lst[1] # 1
print lst[len(lst)] #error
1
你的索引超出了范围。下面是列表索引是怎么工作的:
>>> 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
)。