gpt4 book ai didi

python - 如何使用 JSON 中前一个值的最后一个数字继续新值?

转载 作者:行者123 更新时间:2023-12-01 06:48:42 25 4
gpt4 key购买 nike

这是我的代码:

with open('res.json', 'r') as file1:
json_data = json.load(file1)
for g in json_data['groups']:
try:
for i, group in enumerate(g['resources']):
group['slot'] = i

except:
continue


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

它使每个插槽都像 slot: 1、slot: 2、slot: 3 一样,这很棒。但在 g['resources'] 的下一个子项中,它再次开始,如 slot: 1、slot: 2、slot 3。我希望它将从上一个子项的最后一个数字继续。例如:插槽:4、插槽:5...

谢谢!

最佳答案

为什么不在整个代码中使用一个变量而不是像下面这样的 for 循环:

with open('res.json', 'r') as file1:
json_data = json.load(file1)
i = 1
for g in json_data['groups']:
try:
for group in g['resources']:
group['slot'] = i
i += 1

except:
continue

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

关于python - 如何使用 JSON 中前一个值的最后一个数字继续新值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59118559/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com