Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
293 views
in Technique[技术] by (71.8m points)

python - How to sum the elements of N lists?

can anybody please give me a hint how to aggregate (sum up) specific elements of multiple lists?

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, ...]

I need something like value = sum of index whatever's in c_agent_*[whatever]

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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]

prints

[(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]

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...