Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How do i add upp the values in list of list of lists together?

I have this single list of list of lists, (that I got from doing 3 choose 2 combination on a list of lists):

[([1, 0, 1, 1], [1, 0, 1, 10]), ([1, 0, 1, 1], [1, 1, 0, 100]), ([1, 0, 1, 10], [1, 1, 0, 100])]

so its 3 groups, these 3 groups have 2 lists each, and these 2 lists have 4 integers each

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

I want to add the integers up in these pairs of lists to make one list of sums for each group.
It should look like:

([2,0,2,11], [2,1,1,101], [2,1,1,110])

To show the problem here easily, I simplified the example to "3 groups of 2 lists with 4 integers " but in reality its about "1000 groups of 10 lists of 30 integers".

I tried googling how to do this and got some lambda and zip stuff but I couldn’t get it to work. I tried making a custom loop as well, I mostly got recommended cases of adding list1 to list2 , but i just have one list. I got bunch of errors. I appreciate if anyone could help, thank you.

>Solution :

So here’s a solution using sum and zip:

result = [[sum(row) for row in zip(*pair)] for pair in data]

You can break each call down and add prints to better understand what each part does, I’ll try and explain:

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading