本文介绍了使用公共键-值对对字典列表中的值求和的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何对词典列表中的重复元素求和?
样例列表:
data = [
[
{'user': 1, 'rating': 0},
{'user': 2, 'rating': 10},
{'user': 1, 'rating': 20},
{'user': 3, 'rating': 10}
],
[
{'user': 4, 'rating': 4},
{'user': 2, 'rating': 80},
{'user': 1, 'rating': 20},
{'user': 1, 'rating': 10}
],
]
预期输出:
op = [
[
{'user': 1, 'rating': 20},
{'user': 2, 'rating': 10},
{'user': 3, 'rating': 10}
],
[
{'user': 4, 'rating': 4},
{'user': 2, 'rating': 80},
{'user': 1, 'rating': 30},
],
]
推荐答案
您可以尝试:
from itertools import groupby
result = []
for lst in data:
sublist = sorted(lst, key=lambda d: d['user'])
grouped = groupby(sublist, key=lambda d: d['user'])
result.append([
{'user': name, 'rating': sum([d['rating'] for d in group])}
for name, group in grouped])
# Sort the `result` `rating` wise:
result = [sorted(sub, key=lambda d: d['rating']) for sub in result]
# %%timeit
# 7.54 µs ± 220 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)
更新(更高效的解决方案):
result = []
for lst in data:
visited = {}
for d in lst:
if d['user'] in visited:
visited[d['user']]['rating'] += d['rating']
else:
visited[d['user']] = d
result.append(sorted(visited.values(), key=lambda d: d['rating']))
# %% timeit
# 2.5 µs ± 54 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)
结果:
# print(result)
[
[
{'user': 2, 'rating': 10},
{'user': 3, 'rating': 10},
{'user': 1, 'rating': 20}
],
[
{'user': 4, 'rating': 4},
{'user': 1, 'rating': 30},
{'user': 2, 'rating': 80}
]
]
这篇关于使用公共键-值对对字典列表中的值求和的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!