我不知道为什么会出现此错误或索引超出范围。我在 jupyter 笔记本中使用 Python 3.0

Atu*_*att 0 python jupyter-notebook index-error

import random
from IPython.display import clear_output

dictionary = open("words_50000.txt","r")
dict_5000 = dictionary.readlines()
guess = random.choice(dict_5000).lower().strip('\n')
no_of_letters = len(guess)
game_str = ['-']*no_of_letters
only_length=[]

def word_guesser():
    only_length_words()
    print(dict_5000)


def only_length_words():
    for i in range(len(dict_5000)):
        if len(dict_5000[i].strip('\n'))!=no_of_letters:
            dict_5000.pop(i)    

word_guesser()
Run Code Online (Sandbox Code Playgroud)

-------------------------------------------------- ------------------------- IndexError Traceback (最近一次调用) in () 20 dict_5000.pop(i) 21 ---> 22 word_guesser ()

在 word_guesser() 11 12 def word_guesser(): ---> 13 only_length_words() 14 print(dict_5000) 15

在 only_length_words() 17 def only_length_words(): 18 for i in range(len(dict_5000)): ---> 19 if len(dict_5000[i].strip('\n'))!=no_of_letters: 20 dict_5000。流行音乐(一) 21

IndexError:列表索引超出范围

Ank*_*iya 5

问题是您正在使用pop(),这会破坏列表,但您也在迭代列表。因此,假设您弹出的列表中有一个元素。现在,残缺列表的长度比原始列表短,但 for 循环仍会尝试迭代直到列表的原始长度,这导致IndexError.