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