My data is a list of lists of lists of varying size:
data = [[[1, 3],[2, 5],[3, 7]],[[1,11],[2,15]],.....]]]
What I want to do is return a list of lists with the values of the 2nd element of each list of lists summed - so, 3+5+7 is a list, so is 11+15, etc:
newdata = [[15],[26],...]
Or even just a list of the sums would be fine as I can take it from there:
newdata2 = [15,26,...]
I've tried accessing the items in the list through different forms and structures of list comprehensions, but I can't get seem to get it to the format I want.
Try this one-line approach using list comprehension:
[sum([x[1] for x in i]) for i in data]
Output:
data = [[[1, 3],[2, 5],[3, 7]],[[1,11],[2,15]]]
[sum([x[1] for x in i]) for i in data]
Out[19]: [15, 26]
If you want the output to be a list of list, then use
[[sum([x[1] for x in i])] for i in data]
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