gpt4 book ai didi

python - 纯Python中dict的求和和计数列表

转载 作者:行者123 更新时间:2023-12-01 01:54:14 24 4
gpt4 key购买 nike

我需要帮助。

我有一个字典列表:

[{"title": "Report 1", "value": 1000, "commission": 2000, "user": "user_1"},

{"title": "Report 2", "value": 500, "commission": 300, "user": "user_1"},

{"title": "Report 3", "value": 1500, "commission": 300, "user": "user_2"}]

我需要对数值、按用户分组以及每个用户的总报告进行求和

[{"value": 1500, "commission": 2300, "user": "user_1", "total": 2},

{"value": 1500, "commission": 300, "user": "user_2", "total": 1}]

OBS:纯Python

最佳答案

使用非常简单的迭代方法。

演示:

data = [{"title": "Report 1", "value": 1000, "commission": 2000, "user": "user_1"},
{"title": "Report 2", "value": 500, "commission": 300, "user": "user_1"},
{"title": "Report 3", "value": 1500, "commission": 300, "user": "user_2"}]

d = {}
for i in data:
if i['user'] not in d:
d[i["user"]] = {"value": i["value"], "commission": i["commission"], "user": i['user'], "total": 1}
else:
d[i["user"]]["value"] += i["value"]
d[i["user"]]["commission"] += i["commission"]
d[i["user"]]["total"] += 1
print(d.values())

输出:

[{'commission': 300, 'total': 1, 'user': 'user_2', 'value': 1500}, {'commission': 2300, 'total': 2, 'user': 'user_1', 'value': 1500}]

关于python - 纯Python中dict的求和和计数列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50395812/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com