如何从嵌套字典JSON提取指定ID与red值并生成目标多维数组?
解决方法
原代码存在的问题
- 拼写错误:
acessData应为accessData - 循环逻辑错误:JSON的第一层键是字符串类型的ID(如"100"),不是连续数字索引,
range(len(accessData))无法遍历目标ID范围 - 未覆盖100到300的所有ID,仅处理了JSON中已存在的条目
- 未判断
colors列表是否包含"red",也未处理ID不存在的情况 - 语法错误:
append语句缺少闭合括号
修正后的Python代码
import json y_train = [] # 加载JSON数据 with open('/data.json') as f: access_data = json.load(f) # 将JSON中的字符串ID转为整数,方便后续对比 id_data = {int(id_str): info for id_str, info in access_data.items()} # 遍历100到300的所有ID(包含两端) for current_id in range(100, 301): # 检查ID是否存在,且colors列表包含"red" if current_id in id_data and "red" in id_data[current_id].get("colors", []): y_train.append([current_id, "red"]) else: y_train.append([current_id, "null"]) # 打印格式化结果(可选,用于验证) print("id color") for item in y_train: print(f"{item[0]} {item[1]}")
代码说明
- 把JSON中的字符串ID转为整数,避免字符串与数字对比的类型问题
- 用
range(100, 301)遍历100到300的所有ID(range左闭右开,因此结束值设为301) - 用
get("colors", [])处理ID存在但无colors字段的情况,避免抛出KeyError - 每个条目以
[ID, "red"/"null"]的形式存入多维数组y_train,完全匹配需求
示例输出
id color 100 red 101 red 102 null ... ... 300 red
内容的提问来源于stack exchange,提问作者Matt2918
相关产品推荐
相关产品推荐

