python - 根据值聚合字典数组
问题描述
修订
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: # arrays of dict
if y['type'] not in type_list: #iterate through dicts in array
type_list.append(y['type']) #if not type in list
result.append({'type': y['type'], 'count': []}) #add type in list
return result, type_list
result, type_list = unique_type(data)
empty_results = result
for arr in data:
for num in range(0, len(type_list)):
try:
number = 0
while number < len(type_list):
print(f"{arr[num]['type']} == {result[number]['type']}")
if arr[num]['type'] == result[number]['type']:
result[number]['count'].append(arr[num]['count'])
number += 1
break
else:
number += 1
except IndexError:
# TODO need some way for evaluating if a key is missing from arr compared to result**
print(f"Index Error{result[number]['type']}")
result[number]['count'].append(float('nan'))
我得到的结果
[{'type': 'low', 'count': [100, nan, 100, nan]}, {'type': 'medium', 'count': [45, 45, 45]}, {'type': 'high', 'count': [5, 5]}]
期望的结果
[{'type': 'low', 'count': [100, nan, 100]}, {'type': 'medium', 'count': [45, 45, 45]}, {'type': 'high', 'count': [5, 5, nan]}]
Unique_type()
允许我遍历我的字典数组并创建一个唯一键数组
results
允许我构建我想要的字典数组
在遍历字典数组时,我想确保无论该键是否在结果中退出都有一个值。
原帖
嘿,伙计们,我正在建立一个对我来说有点棘手的模型
a = {'type': 'Low', 'count': 184}
b = {'type': 'Low', 'count': 186}
c = {'type': 'Low', 'count': 97}
new = [a,b,c]
### how do i accomplish below?
result = {'type': low, 'count': [184, 186, 97]}
解决方案
这是一个更通用的解决方案,假设您可以有几种类型:
from itertools import groupby
[{'type': k, 'count': [i['count'] for i in g]}
for k,g in groupby(sorted(new, key=lambda d: d['type']),
key=lambda d: d['type'])
]
输入:
[{'type': 'Low', 'count': 184},
{'type': 'Low', 'count': 186},
{'type': 'Low', 'count': 97},
{'type': 'High', 'count': 1000}]
输出:
[{'type': 'High', 'count': [1000]},
{'type': 'Low', 'count': [184, 186, 97]}]
推荐阅读
- firebase - 使用最终分数更新 Firebase 并显示给用户
- python-3.x - HtmlResponse requests.response 之间的区别
- c# - Unity3D - 当平台旋转时,刚体通过平台对撞机进行定相
- c# - MouseUp 和 MouseDown 不适用于 usercontrol 的子级
- flutter - 颤振中的 simple_slider 小部件不起作用
- c++ - 如何使用 C++ SFML 中的数据/文本文件为 Breakout 游戏创建砖块布局?
- java - 如何在硒中做到这一点
- php - Laravel 中的 405 方法不允许异常
- node.js - 找到等于具有非数组字段的任何一个数组元素查询的文档
- flutter - 图像选择器扫描为空