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

如何通过循环扩展单字典列表并解决list index out of range错误

解决方法:生成包含多个重复字典的列表

你当前的代码只是重复把原始数据写入文件,完全没修改_items列表的内容,自然得不到想要的结果,而list index out of range错误大概率是你在其他未展示的代码里错误访问了列表索引(比如列表只有1个元素,却试图访问索引1及以上的位置)。

要生成包含5个相同字典的_items列表,有两种简洁的实现方式:

方式一:列表推导式(推荐)

直接用列表推导式生成5个独立的字典副本:

import json

# 假设你的data是包含"_items"键的字典
template = data['_items'][0]
# 用copy()创建独立副本,避免后续修改一个字典影响所有
data['_items'] = [template.copy() for _ in range(5)]

# 写入文件
with open('目标文件.json', 'w', encoding='utf-8') as file:
    json.dump(data, file, indent=4, ensure_ascii=False)

方式二:循环添加

如果习惯用循环逐步添加元素:

import json

template = data['_items'][0]
data['_items'] = []  # 清空原列表
for _ in range(5):
    data['_items'].append(template.copy())

# 写入文件
with open('目标文件.json', 'w', encoding='utf-8') as file:
    json.dump(data, file, indent=4, ensure_ascii=False)

注意点

必须用template.copy()而不是直接复用原字典,因为字典是引用类型,如果直接写[template]*5,列表里的所有元素都会指向同一个字典对象,后续修改其中任意一个字典的内容,其他所有字典都会跟着变。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.29 19:32:27