You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何解决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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.25 22:39:25