我不知道为什么会出现此错误或索引超出范围。我在 jupyter 笔记本中使用 Python 3.0
I don't know why I'm getting this error or index out of range. I'm using Python 3.0 in jupyter notebook
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
问题是您使用的是 pop()
,它破坏了列表,但您也在遍历列表。因此,假设您弹出的列表中有一个元素。现在,残缺列表的长度比原始列表短,但 for 循环仍将尝试迭代直到列表的原始长度,这导致 IndexError
.
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
问题是您使用的是 pop()
,它破坏了列表,但您也在遍历列表。因此,假设您弹出的列表中有一个元素。现在,残缺列表的长度比原始列表短,但 for 循环仍将尝试迭代直到列表的原始长度,这导致 IndexError
.