Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Summing 2nd list items in a list of lists of lists

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.

like image 464
mk8efz Avatar asked Dec 08 '22 22:12

mk8efz


1 Answers

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]
like image 174
MaThMaX Avatar answered Dec 11 '22 09:12

MaThMaX