Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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]
like image 795
saun jean Avatar asked Dec 06 '25 08:12

saun jean


2 Answers

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.

like image 179
NPE Avatar answered Dec 08 '25 20:12

NPE


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.

like image 27
Jan Pöschko Avatar answered Dec 08 '25 20:12

Jan Pöschko