基于type值聚合字典数组 修复nan填充错误实现预期聚合结果
Python按type字段聚合嵌套字典数组方法
需求背景
基础需求
给定多个包含相同type的字典组成的列表,将同type的count值合并为列表,示例:
a = {'type': 'Low', 'count': 184} b = {'type': 'Low', 'count': 186} c = {'type': 'Low', 'count': 97} new = [a,b,c] # 期望结果 result = {'type': 'Low', 'count': [184, 186, 97]}
升级需求
对三层嵌套字典数组进行聚合,不存在的type对应的count位置填充nan,保证每个type的count列表长度等于输入子数组的总数量。
示例输入数据:
data = [[{'type': 'low', 'count': 100}, {'type': 'medium', 'count': 45}, {'type': 'high', 'count': 5}], [{'type': 'medium', 'count': 45}, {'type': 'high', 'count': 5}], [{'type': 'low', 'count': 100}, {'type': 'medium', 'count': 45}]]
期望输出结果:
[{'type': 'low', 'count': [100, nan, 100]}, {'type': 'medium', 'count': [45, 45, 45]}, {'type': 'high', 'count': [5, 5, nan]}]
原有代码问题分析
原有代码循环逻辑混乱,依赖索引匹配type,未对每个子数组的所有type做存在性校验,导致nan填充位置错误、count列表长度不符合要求。
修复后代码
data = [[{'type': 'low', 'count': 100}, {'type': 'medium', 'count': 45}, {'type': 'high', 'count': 5}], [{'type': 'medium', 'count': 45}, {'type': 'high', 'count': 5}], [{'type': 'low', 'count': 100}, {'type': 'medium', 'count': 45}]] def unique_type(data): result = [] type_list = [] for x in data: for y in x: if y['type'] not in type_list: type_list.append(y['type']) result.append({'type': y['type'], 'count': []}) return result, type_list result, type_list = unique_type(data) # 核心修改部分:遍历每个子数组,先转成type-count映射再统一填充 for arr in data: # 把当前子数组转成{type: count}的字典,方便快速查找 arr_map = {item['type']: item['count'] for item in arr} # 按唯一type顺序逐个填充 for idx, typ in enumerate(type_list): result[idx]['count'].append(arr_map.get(typ, float('nan'))) print(result)
输出结果
运行后即可得到预期结果:
[{'type': 'low', 'count': [100, nan, 100]}, {'type': 'medium', 'count': [45, 45, 45]}, {'type': 'high', 'count': [5, 5, nan]}]
内容的提问来源于stack exchange,提问作者toasty89
相关产品推荐
相关产品推荐

