Python:n个列表的元素总数 [英] Python: Sum of element for n-lists
本文介绍了Python:n个列表的元素总数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
有人可以给我一个提示,如何汇总(汇总)多个列表的特定元素吗?
can anybody please give me a hint how to aggregate (sum up) specific elements of multiple lists?
例如,我有20个名称模式相似的列表,每个列表代表相应家庭(代理商)随时间的消费支出(即指数):
For example I have 20 lists with a similar name pattern, each representing consumption spending over time (i.e. index) of the corresponding household (agent):
c_agent_0 = [10.0, 11.0, ...]
.
.
.
c_agent_19 = [8.0, 9.0, ...]
在c_agent _ * [无论如何]
I need something like value = sum of index whatever in c_agent_*[whatever]
谢谢!
推荐答案
使用 zip 将列表组合"为一个,然后将每个索引的元素求和:
Use zip to "combine" lists into single one, then sum elements for each index:
c_agent_0 = [10.0, 11.0, 12.0, 13.0, 14.0]
c_agent_1 = [1.1, 12.3, 14.2, 13.2, 14.3]
c_agent_2 = [1.4, 12.1, 14.5, 13.1, 14.2]
zipped_list = zip(c_agent_0, c_agent_1, c_agent_2)
print zipped_list
print [sum(item) for item in zipped_list]
打印
[(10.0, 1.1, 1.4), (11.0, 12.3, 12.1), (12.0, 14.2, 14.5), (13.0, 13.2, 13.1), (14.0, 14.3, 14.2)]
[12.5, 35.4, 40.7, 39.3, 42.5]
这篇关于Python:n个列表的元素总数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文