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

如何将JSON中resources的slot值依次递增1?

问题分析与解决方案

嗨,这问题我熟!你代码里的问题很明确:每次循环时你都先把group['slot']重置为0,然后再加1,所以不管循环多少次,每个组的slot最后都是1,根本没法实现递增。

解决思路

要实现slot从1开始依次递增,我们需要一个不受循环重置影响的计数器,或者用Python内置的enumerate函数自动生成递增序号。


方法1:使用外部计数器

在循环前初始化一个计数器变量,每次循环给当前组赋值后,让计数器自增:

import json  # 别忘了导入json模块!你原代码里没写,运行会报错的

with open('res1536.json', 'r') as json_file:
    json_data = json.load(json_file)

# 初始化计数器,从1开始
slot_counter = 1
for group in json_data['resources']:
    group['slot'] = slot_counter
    slot_counter += 1

with open("RES_Edited.JSON", 'w') as json_edited:
    json.dump(json_data, json_edited, indent=1)

方法2:使用enumerate函数(更Pythonic)

enumerate可以同时获取循环的索引和元素,设置start=1就能让索引从1开始,直接赋值给slot即可:

import json

with open('res1536.json', 'r') as json_file:
    json_data = json.load(json_file)

# enumerate的start参数设为1,让序号从1开始
for slot_num, group in enumerate(json_data['resources'], start=1):
    group['slot'] = slot_num

with open("RES_Edited.JSON", 'w') as json_edited:
    json.dump(json_data, json_edited, indent=1)

补充提醒

你原代码里漏掉了import json语句,运行时会抛出NameError,记得加上哦!

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.14 08:47:46