数组列表索引超出范围
问题描述:
我有一个大小为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
答
你的指数是出界。这里是列表索引是如何工作的:
>>> 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
)的索引。
答
这是预期的行为。如果您有一个list
其len
的x
,那么x
索引是未定义的。
如:
lst = [0,1]
print len(lst) # 2
print lst[0] # 0
print lst[1] # 1
print lst[len(lst)] #error
+0
作为附录:这是因为Python列表是[zero-indexed](http:// en.wikipedia.org/wiki/Zero-based_numbering)。 – thegrinner 2013-03-14 17:28:23
我打赌'i> = 155'。那么'resList'(你得到索引的地方)和'resultss'(你使用索引的地方)之间的关系是什么? – hughdbrown 2013-03-14 17:25:09
你错了,打印出来,它是155 – miik 2013-03-14 17:26:16
修正:'I> = 155'。 – hughdbrown 2013-03-14 17:26:53