saun jean
saun jean

Reputation: 759

How to add numbers in nested Python lists

I have a list

[["Sunday", 7, 0], ["Sunday", 2, 0], ["Monday", 1, 5], ["Tuesday", 5, 0], ["Thursday", 2, 0], ["Friday", 3, 0], ["Friday", 1, 0], ["Saturday", 4, 0], ["Monday", 8, 0], ["Monday", 1, 0], ["Tuesday", 1, 0], ["Tuesday", 2, 0], ["Wednesday", 0, 5]]

Can I add the values in the lists to get sums like

["I dont need this value", 37, 10]

Upvotes: 2

Views: 879

Answers (5)

NPE
NPE

Reputation: 500257

This is precisely what reduce() is made for:

In [4]: reduce(lambda x,y:['',x[1]+y[1],x[2]+y[2]], l)
Out[4]: ['', 37, 10]

where l is your list.

This traverses the list just once, and naturally lends itself to having different -- possibly more complicated -- expressions for computing the three terms.

Upvotes: 8

Jan Pöschko
Jan Pöschko

Reputation: 5560

For a flexible number of values per item and even less characters, you can use

In [1]: [sum(values) for values in zip(*l)[1:]]
Out[1]: [37, 10]

zip yields tuples of combinations of corresponding items (i.e. a tuple with all the 1st items, a tuple with all the 2nd items, etc), which can be summed up each (except for the first string value). Of course, you can still prepend "" or whatever you like at the beginning if needed.

Upvotes: 5

Rusty Rob
Rusty Rob

Reputation: 17173

of course, the ultimate:

>>> stuff=[["Sunday", 7, 0], ["Sunday", 2, 0], ["Monday", 1, 5], ["Tuesday", 5, 0], ["Thursday", 2, 0], ["Friday", 3, 0], ["Friday", 1, 0], ["Saturday", 4, 0], ["Monday", 8, 0], ["Monday", 1, 0], ["Tuesday", 1, 0], ["Tuesday", 2, 0], ["Wednesday", 0, 5]]
>>> stuff=zip(*stuff)
>>> map(sum,stuff[1:])
[37, 10]

Upvotes: 4

Rusty Rob
Rusty Rob

Reputation: 17173

>>> stuff=[["Sunday", 7, 0], ["Sunday", 2, 0], ["Monday", 1, 5], ["Tuesday", 5, 0], ["Thursday", 2, 0], ["Friday", 3, 0], ["Friday", 1, 0], ["Saturday", 4, 0], ["Monday", 8, 0], ["Monday", 1, 0], ["Tuesday", 1, 0], ["Tuesday", 2, 0], ["Wednesday", 0, 5]]
>>> sum(j for i,j,k in stuff),sum(k for i,j,k in stuff)
(37, 10)

Upvotes: 3

dani herrera
dani herrera

Reputation: 51655

I assign your list to l:

l = [ your list .... ]
['dont needed', sum( [ x[1] for x in l ] ), sum(  [x[2] for x in l ] ) ]

Result:

['dont needed', 37, 10]

Upvotes: 4

Related Questions