Cyt*_*tan 1 python dictionary list-comprehension sum list
一直在考虑如果可能的话如何将其转换为单衬:
\nactivities = \n[ {'type': 'Run', 'distance': 12345, 'other_stuff': other ...}, \n {'type': 'Ride', 'distance': 12345, 'other_stuff': other ...}, \n {'type': 'Swim', 'distance': 12345, 'other_stuff': other ...} ] \n\nRun Code Online (Sandbox Code Playgroud)\n目前正在使用:
\ngrouped_distance = defaultdict(int)\nfor activity in activities: \n act_type = activity['type']\n grouped_distance[act_type] += activity['distance']\n\n# {'Run': 12345, 'Ride': 12345, 'Swim': 12345} \nRun Code Online (Sandbox Code Playgroud)\n已尝试
\n grouped_distance = {activity['type']:[sum(activity['distance']) for activity in activities]}
\n这不起作用,它说 Activity['type'] 未定义。
编辑
\n修复了 @Samwise 注意到的一些变量拼写错误
更新: \n对已发布的所有解决方案进行了一些基准测试。\n1000 万项,有 10 种不同类型:
\n方法 1 (Counter): 7.43s
\n方法 2 (itertools @chepner): 8.64s
\n方法 3 (groups @Dmig): 19.34s
\n方法 4 (pandas @db): 32.73s
\n方法 5 (Dict @db): 10.95秒
在 Raspberry Pi 4 上进行测试,以进一步查看差异。\n如果我错误地“命名”该方法,请纠正我。
\n谢谢大家,@Dmig、@Mark、@juanpa.arrivilillaga 激起了我对表演的兴趣。更短/更整洁 \xe2\x89\xa0 更高的性能。只是想问我是否以单行形式写它,以便看起来更整洁,但我学到的东西远不止于此。
\n你的解决方案本身就很好,但如果你真的想要一行:
act = [{'type': 'run', 'distance': 4}, {'type': 'run', 'distance': 3}, {'type': 'swim', 'distance': 5}]
groups = {
t: sum(i['distance'] for i in act if i['type'] == t)
for t in {i['type'] for i in act} # set with all possible activities
}
print(groups) # {'run': 7, 'swim': 5}
Run Code Online (Sandbox Code Playgroud)
UPD:我做了一些性能研究,将此答案与使用group(sortedby(...)). 事实证明,在 1000 万个条目和 10 种不同类型上,这种方法输给group(sortedby(...))了18.14秒数10.12。因此,虽然它更具可读性,但在较大的列表上,尤其是在其中包含更多不同类型的情况下,效率较低(因为它为每个不同类型迭代初始列表一次)。
但请注意,从问题开始的直接方法只需几5秒钟!
这个答案只是出于教育目的而显示一句台词,问题的解决方案具有更好的性能。你不应该用这个来代替有问题的,除非,正如我所说,你真的想要/需要一句台词。