IndexError:列表索引超出范围.我想不出怎样才能摆脱它


dictionary = {"a": 1, "b": 2, "c": 3, "d": 4, "e": 5, "f": 6, "g": 7, "h": 8, "i": 9, "j": 10, "k": 11, "l": 12, "m": 13, "n": 14, "o": 15, "p": 16, "q": 17, "r":18}
word = "redf"
word_list = list(word)
num_of_letters = len(word)
times_looped = 0
while num_of_letters >= times_looped:
if times_looped <= num_of_letters:
replacement_num = dictionary.get(word_list[times_looped])
word_list.pop(times_looped)
word_list.insert(times_looped, replacement_num)
times_looped += 1
print(word_list)
pass

问题是索引号导致您分配的num_of_letters和while循环之间的范围冲突。

通过在

后面加-1来解决这个问题:
num_of_letters = len(word)-1

希望对您有所帮助

最新更新