我不知道为什么我得到这个错误或索引超出范围。我正在jupyter noteb中使用python3.0

2024-05-26 21:54:13 发布

您现在位置:Python中文网/ 问答频道 /正文

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 (most recent call last) in () 20 dict_5000.pop(i) 21 ---> 22 word_guesser()

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

in 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.pop(i) 21

IndexError: list index out of range


Tags: ofnoinonlylendefrangepop
1条回答
网友
1楼 · 发布于 2024-05-26 21:54:13

问题是您正在使用pop(),这会破坏列表,但您也在对列表进行迭代。所以,假设列表中有一个元素,你弹出了。现在,残缺列表的长度比原始列表短,但是for循环仍然会尝试迭代,直到列表的原始长度,这会导致IndexError。你知道吗

相关问题 更多 >

    热门问题