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

为何循环赋值变量触发list index out of range错误?如何修复?

问题场景

尝试遍历JSON结构提取指定条目时触发IndexError,具体代码与现象如下:

原始代码:

import ast

json_message = ast.literal_eval( f"{   { 'B': [{'a': 'A', 'f': '1', 'l': '0.00000000'}, {'a': 'B', 'f': '2', 'l': '0.00000000'}, {'a': 'C', 'f': '3', 'l': '0.00000000'}]} }" )

currency = ["'A'", "'C'"] 
for x in range(len(currency)):
    aaa = currency[x]
    print(aaa)
    # 执行以下代码触发错误
    msg = [y for y in json_message['B'] if y['a'] == aaa]
    print(msg)
    print(msg[0])

运行现象:

  • 打印aaa输出'A'
  • 打印msg输出[],随后触发IndexError: list index out of range
  • 直接使用字符串常量'A'时,代码能正常返回目标条目:
msg = [y for y in json_message['B'] if y['a'] == 'A']
print(msg[0])  # 输出 {'a': 'A', 'f': '1', 'l': '0.00000000'}
问题原因

currency列表中的元素是带外层单引号的字符串("'A'"、"'C'"),而json_message['B']里的y['a']值是不带外层单引号的纯字符串("A"、"C")。两者做相等判断时,实际是比较"'A'" == "A",结果为False,因此列表推导式返回空列表,访问msg[0]自然触发索引越界错误。

修复方案

有两种可行的修复方式:

  • 方式一:直接修改currency列表,去掉元素外层的单引号
currency = ["A", "C"] 
  • 方式二:若无法修改currency原始数据,可在使用时去除字符串两端的单引号
aaa = currency[x].strip("'")

内容的提问来源于stack exchange,提问作者Dalalama231123

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.14 13:35:44