如何解决Python中的IndexError: list index out of range错误?
问题分析与解决
错误原因
你遇到的IndexError: list index out of range是循环边界处理错误导致的:
word是"redf",长度为4,word_list的有效索引范围是0到3(列表索引从0开始)。- 你的
while循环条件是num_of_letters >= times_looped,当times_looped等于4时仍会进入循环,此时访问word_list[4]超出了列表的索引范围,触发错误。 - 内部的
if条件times_looped <= num_of_letters也存在同样的边界问题。
修复后的代码
调整循环边界,同时简化元素替换逻辑(无需pop和insert,直接赋值更高效):
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 times_looped < num_of_letters: replacement_num = dictionary.get(word_list[times_looped]) word_list[times_looped] = replacement_num times_looped += 1 print(word_list)
更简洁的写法
用列表推导式可以一步完成转换,代码更简洁易读:
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 = [dictionary.get(char) for char in word] print(word_list)
内容的提问来源于stack exchange,提问作者sirpixelz
相关产品推荐
相关产品推荐

