Python遍历嵌套JSON分别筛选统计灯具、开关设备的实现方法
解决方案
直接按需求拆分两个独立循环分别处理灯具和开关即可,示例代码如下:
完整实现代码
# 筛选符合条件的设备列表 lights = [item for item in data["devices"] if "20" in item["devId"]["dps"]] switches = [item for item in data["devices"] if "1" in item["devId"]["dps"]] # 灯具处理循环 light_index = 1 for light_item in lights: light_item["address"] = "light_{}".format(light_index) # 输出设备信息 print(light_item["address"]) print(light_item["name"]) print(light_item["id"]) print(light_item["ip"]) print(light_item["key"]) print(light_item["ver"]) light_index += 1 # 开关处理循环 switch_index = 1 for switch_item in switches: switch_item["address"] = "switch_{}".format(switch_index) # 输出设备信息 print(switch_item["address"]) print(switch_item["name"]) print(switch_item["id"]) print(switch_item["ip"]) print(switch_item["key"]) print(switch_item["ver"]) switch_index += 1
样例运行输出
light_1 Office Light ebfc16d57ed374932cjqfk 192.168.1.147 805217605357161b 3.3 switch_1 Switch Family Room Sconces 017743508caab5f385a7 192.168.1.155 7b8f2415ac96dfea 3.3
注意点
你之前的写法里range(1, totalnum)会漏掉最后一个设备,因为range区间是左闭右开,实际遍历元素时直接迭代列表本身更不容易出索引错误。
内容的提问来源于stack exchange,提问作者Steven Bailey
相关产品推荐
相关产品推荐

