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]
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With