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'中总是空的。 –