简体   繁体   English

用Python方式纵向和横向汇总列表字典

[英]Pythonic way to sum vertically and horizontally a dictionary of list

dict = {1:[1,2,3,4],2:[5,5,5,3],3:[5,6,7,8]}

I have seen a pythonic way to sum each list of the dictionary, but is there a pythonic way to sum all corresponding elements of the lists in the dictionary? 我已经看到了一种pythonic的方法来汇总字典的每个列表,但是有pythonic的方法来汇总字典中的列表的所有对应元素吗?

E.g.:
1+5+5 are the first elements of all the lists
2+5+6 are the second elements of all the lists

Currently I am using a double for loop. 目前,我正在使用double for循环。

Since you don't really care about the order in which items are added you can just use zip on dict.values in a list comprehension: 由于您实际上并不关心项目的添加顺序,因此您可以对列表理解中的dict.values使用zip

d = {1:[1,2,3,4],2:[5,5,5,3],3:[5,6,7,8]}

print([sum(i) for i in zip(*d.values())])

Output: 输出:

[11, 13, 15, 15]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM