如何处理嵌套JSON结构,批量提取Quantity键值并求和?
问题:统计Haarlem地区充电枪总数
输入JSON结构
[ { "IsRecentlyVerified": true, "AddressInfo": { "Town": "Haarlem" }, "Connections": [ { "PowerKW": 17, "Quantity": 1 } ], "NumberOfPoints": 1 }, { "IsRecentlyVerified": true, "AddressInfo": { "Town": "Haarlem" }, "Connections": [ { "PowerKW": 17, "Quantity": 1 }, { "PowerKW": 17, "Quantity": 1 } ], "NumberOfPoints": 1 } ]
需求说明
筛选出AddressInfo.Town为Haarlem的条目,统计所有Connections列表内字典的Quantity值总和(示例中总和应为3)。需处理Quantity键可能不存在的情况。
当前代码问题
现有代码仅检查每个Connections列表的第一个字典是否存在Quantity,且错误地将站点数量和充电枪数量累加在同一个变量中,导致结果错误。
解决方案
修正后的代码
def calculate_total_charging_poles(): total_poles = 0 for station in ev_list: # 安全获取AddressInfo,避免键不存在报错 address_info = station.get("AddressInfo", {}) if address_info.get("Town") == "Haarlem": # 遍历当前站点的所有Connections条目 for connection in station.get("Connections", []): # 检查当前Connection是否包含Quantity键 if "Quantity" in connection: total_poles += connection["Quantity"] # 可选:针对无Quantity的情况添加日志 # else: # print(f"Connection missing Quantity field: {connection}") print(f"There are at least {total_poles} charging poles available.") return total_poles total_poles = calculate_total_charging_poles()
关键优化点
- 遍历逻辑简化:直接遍历
ev_list中的每个站点字典,无需通过索引遍历,代码更简洁易读。 - 安全取值处理:使用
dict.get()方法获取嵌套键,避免因某个站点缺少AddressInfo或Connections字段而抛出异常。 - 逐个检查Connection:对每个站点的所有
Connections条目单独校验Quantity是否存在,确保不会遗漏任何一个充电枪数量。 - 变量职责清晰:用
total_poles专门统计充电枪总数,避免和站点数量混淆(若需统计站点数,可单独定义变量)。
关于遍历所有Connections的说明
Python中遍历列表无需手动指定索引范围,直接使用for item in list:语法即可遍历列表的全部元素,等价于你提到的[0:end]效果。
内容的提问来源于stack exchange,提问作者JvW
相关产品推荐
相关产品推荐

