首页 > 解决方案 > 如何使用 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)

这只是第一次尝试。

标签: pythonpython-3.xlistdictionarymapreduce

解决方案


这是一个尝试使用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; 这与您的预期输出不同,但我猜这就是您想要的?


推荐阅读