2015-11-07 146 views
1

我試圖做出代約3克的代碼,但如果我運行下面的代碼,它給我的錯誤:列表索引超出範圍

list index out of range 

在行功能third_word就行next_word = word_list[x+2]

def third_word(key): 
    third = {} 
    next_word = word_list[x+2] 

    if next_word not in third: 
     third[next_word] = 1 

    elif next_word in third: 
     third[next_word] += 1  

    return third 

x = 0 
for word in word_list: 
    key = (word_list[x], word_list[x+1]) 

    if key not in follow_ups: 
     follow_ups[key] = third_word(key) 

    x += 1 
+0

什麼是'word_list'? –

+0

'x'將從'0'運行到'len(word_list)-1'。如果最後一個鍵不在'follow_ups'中,那麼你會嘗試用'len(word_list)+ 1'來索引,這會導致錯誤。類似地,倒數第二個鍵將使用'len(word_list)',這也是越界。另外,'third'沒有做任何事情,因爲它不是全局的,並且在'third_word'中總是空的。 –

回答

0

對於word_list中的每個單詞,您想要訪問元素x + 2。假設你的word_list有n個索引從0到n-1的元素,那麼當我們在列表的最後一次迭代時,你想訪問第n + 1個詞,這顯然是超出界限的。

我建議你生成範圍,而不是指數,去:

for x in range(len(word_list) - 2): 
    ... 
+0

你可能是指'len(word_list)-2' – Azad