"list index out of range" 迭代字符串

"list index out of range" while iterating strings

我收到错误“列表超出范围。虽然我找到了这个错误的另一种方法,但我能知道如何解决这个错误。

len 在这种情况下是 5,所以范围是创建一个从 0 到 5 的范围,而你的列表索引从 0 到 4。

您可以将该行重写为:

for i in range(len(words)-1):

否则,如果您只需要单词而不需要索引,您可以只写

for word in words:

最后,如果您同时需要单词和索引,可以使用 enumerate()

for i, word in enumerate(words, start=0):

尝试将范围设置为:

len(words) - 1

因此 for 循环将是:

for i in range(len(words)-1):

len(words) 将 return 长度的文字数字计数,但是在遍历范围时,范围从 0 开始,因此您希望范围为 len(words) - 1

您不需要使用 len() 函数或 range() 函数。您可以只使用:

for i in words:
  synset = wordnet.synsets(i)
  print(i + synset)
len() 

在这种情况下函数给出的输出为 5,因为计数器从 1 而不是 0 开始。 所以如果你想遍历列表,使用:

for i in range(len(words) - 1):

这将计数到最后一个元素,而不是遍历并给出错误。

正如大家所说,问题不在于您的 for loop。问题是 'the'synset 因为 'the' 的同义词集条目不存在。您可以用以下代码替换您的代码:

for i in range(len(words)):
    synset = wordnet.synsets(words[i])
    if synset:
        print ("Synonym of the word "+words[i]+" in the list is: "+synset[0].lemmas()[0].name())
    else:
        print ("Synonym of the word "+words[i]+" not found in the list")

输出:

Synonym of the word After in the list is: after
Synonym of the word getting in the list is: acquiring
Synonym of the word the not found in the list
Synonym of the word proper in the list is: proper
Synonym of the word co-ordinates in the list is: coordinate

希望以上代码对您有所帮助!