我不知道为什么我得到这个错误或索引超出范围。我在Jupyter Notebook中使用Python 3.0

时间:2018-06-27 07:36:27

标签: 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()
  

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

     word_guesser()中的

       11        12 def word_guesser():   ---> 13 only_length_words()        14次打印(dict_5000)        15

     

在only_length_words()中        17 def only_length_words():        对于范围内的我18(len(dict_5000)):   ---> 19如果len(dict_5000 [i] .strip('\ n'))!= no_of_letters:        20 dict_5000.pop(i)        21

     

IndexError:列表索引超出范围

1 个答案:

答案 0 :(得分:2)

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