Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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]

like image 550
JohnDoe Avatar asked Jul 17 '13 11:07

JohnDoe


3 Answers

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]
like image 172
alecxe Avatar answered Oct 22 '22 15:10

alecxe


You can create a list of lists, and then use numpy arrays:

import numpy as np
c_agent_0 = [10.0, 11.0, 12.0]
c_agent_1 = [13.0, 14.0, 15.0]
c_agent_2 = [16.0, 17.0, 18.0]
mylist = [c_agent_0, c_agent_1, c_agent_2]
mylist = sum(map(np.array, mylist))
print mylist[0]

Note that a list comprehension is most likely faster; this is just a solution with numpy :).

like image 42
TerryA Avatar answered Oct 22 '22 15:10

TerryA


If you want to do this to all the columns, then alecxe's answer is best, if you only want a single one (or a subset), then it's a little wasteful as it does a lot of unnecessary processing.

For a single column (the third in this case):

sum([c_agent[2] for c_agent in c_agents])

We use the sum() built in to sum, and a simple list comprehension to get the nth item from each list.

As noted in my comment, this assumes you have a list of lists, as opposed to a load of variables:

c_agents = [c_agent_0, c_agent_1, ...]

Using data structures effectively will make your code much, much better.

The previously mentioned zip() based solution can also easily be modified to work with this data structure:

[sum(column) for column in zip(*c_agent_s)]

Here we use the * operator to unpack the list as the arguments for zip().

like image 26
Gareth Latty Avatar answered Oct 22 '22 13:10

Gareth Latty