python - 如何使用 Python 映射和减少我的字典列表
问题描述
我有这个字典列表:
[{'topic_id': 1, 'average': 5.0, 'count': 1}, {'topic_id': 1, 'average': 8.0, 'count': 1}, {'topic_id': 2, 'average': 5.0, 'count': 1}]
我想映射和减少(或组)有这样的结果:
[
{
'topic_id': 1,
'count': 2,
'variance': 3.0,
'global_average': 6.5
},
{
'topic_id': 2,
'count': 1,
'variance': 5.0,
'global_average': 5.0
}
]
计算方差(最大平均值 - 最小平均值)并计算项目数的东西。
我已经做了什么:
在我尝试对改变字典结构的计数进行求和,并使键成为 topic_id 并为计数赋值之前,我的结果是:
result = sorted(dict(functools.reduce(operator.add, map(collections.Counter, data))).items(), reverse=True)
这只是第一次尝试。
解决方案
这是一个尝试使用itertools.groupby
基于以下数据对数据进行分组topic_id
:
import itertools
data = [{'topic_id': 1, 'average': 5.0, 'count': 1}, {'topic_id': 1, 'average': 8.0, 'count': 1}, {'topic_id': 2, 'average': 5.0, 'count': 1}]
# groupby
grouper = itertools.groupby(data, key=lambda x: x['topic_id'])
# holder for output
output = []
# iterate over grouper to calculate things
for key, group in grouper:
# variables for calculations
count = 0
maxi = -1
mini = float('inf')
total = 0
# one pass over each dictionary
for g in group:
avg = g['average']
maxi = avg if avg > maxi else maxi
mini = avg if avg < mini else mini
total += avg
count += 1
# write to output
output.append({'total_id':key,
'count':count,
'variance':maxi-mini,
'global_average':total/count})
给这个output
:
[{'total_id': 1, 'count': 2, 'variance': 3.0, 'global_average': 6.5},
{'total_id': 2, 'count': 1, 'variance': 0.0, 'global_average': 5.0}]
请注意,'variance'
第二组的 ;0.0
在这里而不是5.0
; 这与您的预期输出不同,但我猜这就是您想要的?
推荐阅读
- swift - SwiftUI-App 不符合协议“App”
- javascript - Javascript - 使用“useEffect()”和“useState”未定义来自异步获取的反应数据
- python - 如何制作“可迭代变量”?
- python - Pyinstaller exe不运行程序
- javascript - 拒绝框架“https://www.youtube.com/”,因为它违反了以下内容安全政策指令:“frame-src 'X'
- python-3.x - python osmnx - 从葡萄牙提取所有网络
- python - Atlassian API 在 API 中附加文件时抛出错误
- docker - 如何将已安装的文件夹删除到 docker 容器
- excel - 获取 Excel 中给定标题名称列的最后一个值
- css - 带有表单输入的引导表不会缩小