Python列表/字典理解将字典列表键与同一字典中的另一个键求和

Cyt*_*tan 1 python dictionary list-comprehension sum list

一直在考虑如果可能的话如何将其转换为单衬:

\n
activities = \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\n
Run Code Online (Sandbox Code Playgroud)\n

目前正在使用:

\n
grouped_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} \n
Run Code Online (Sandbox Code Playgroud)\n

已尝试
\n grouped_distance = {activity['type']:[sum(activity['distance']) for activity in activities]}
\n这不起作用,它说 Activity['type'] 未定义。

\n

编辑
\n修复了 @Samwise 注意到的一些变量拼写错误

\n

更新: \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秒

\n

在 Raspberry Pi 4 上进行测试,以进一步查看差异。\n如果我错误地“命名”该方法,请纠正我。

\n

谢谢大家,@Dmig、@Mark、@juanpa.arrivilillaga 激起了我对表演的兴趣。更短/更整洁 \xe2\x89\xa0 更高的性能。只是想问我是否以单行形式写它,以便看起来更整洁,但我学到的东西远不止于此。

\n

Dmi*_*mig 6

你的解决方案本身就很好,但如果你真的想要一行:

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秒钟!

这个答案只是出于教育目的而显示一句台词,问题的解决方案具有更好的性能。你不应该用这个来代替有问题的,除非,正如我所说,你真的想要/需要一句台词。

  • 这回答了问题,但值得注意的是,您将具有 O(n) 性能的非单行代码换成了具有 O(n^2) 性能的单行代码(尽管对集合有一点帮助)。 (3认同)
  • @Cytan 请注意,代码多次迭代列表“act”。它适用于您举办的每种类型的活动。因此,如果您有一个包含 10 个项目和 5 种类型的列表,则它需要查看 50 个项目,而不是原始代码中的仅 10 个项目。 (3认同)
  • @Cytan我已经更新了答案以包含有关建议解决方案的基准性能的更多信息 (2认同)