2013-03-14 139 views
1

我有一個大小爲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 
+0

我打賭'i> = 155'。那麼'resList'(你得到索引的地方)和'resultss'(你使用索引的地方)之間的關係是什麼? – hughdbrown 2013-03-14 17:25:09

+0

你錯了,打印出來,它是155 – miik 2013-03-14 17:26:16

+0

修正:'I> = 155'。 – hughdbrown 2013-03-14 17:26:53

回答

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)的索引。

2

這是預期的行爲。如果您有一個listlenx,那麼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