谁能给我一个提示如何聚合(总结)多个列表的特定元素?
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, ...]
我需要类似 value = sum of index what's in c_agent_*[whatever]
I need something like value = sum of index whatever's 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]
这篇关于如何对 N 个列表的元素求和?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持html5模板网!
列表字典中的总和值Sum values in a dict of lists(列表字典中的总和值)
如何在 Python 中对文本文件中的数字求和How to sum numbers from a text file in Python(如何在 Python 中对文本文件中的数字求和)
什么是类似于 sum() 的减法函数,用于减去列表中What is a subtraction function that is similar to sum() for subtracting items in list?(什么是类似于 sum() 的减法函数,用于减去列表中的
Python 等价于 sum() 使用 xor()Python equivalent of sum() using xor()(Python 等价于 sum() 使用 xor())
python中的求和矩阵列sum matrix columns in python(python中的求和矩阵列)
N个列表元素的总和pythonsum of N lists element-wise python(N个列表元素的总和python)