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 to sum the values from same index from multiple lists within multiple lists?

I have a list that contains multiple lists wich at the same time, those lists contain multiple lists. For simplicity lets say I have:

x = [
    [[1, 0], [0, 0], [0 , 0], [1, 0], [0, 0], [0, 0], [0, 0], [0, 0], [0, 0]]
    ]

Lets consider the following variable:

y = [[0, 0], [0, 2], [0 , 0], [0, 0], [0, 1], [0, 0], [0, 1], [0, 0], [0, 1]]

Is there a more pythonic way to obtain:

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

res = [[1, 0], [0, 2], [0 , 0], [1, 0], [0, 1], [0, 0], [0, 1], [0, 0], [0, 1]]

Other than:

for i in range(len(y)):
    res.append([y[i][0] + x[0][i][0], y[i][1] + x[0][i][1]])

>Solution :

You can use list comprehensions and do t in 1 line:

x_list = x[0]  # Not sure why x is inside a list but I'm going with it
result = [[sum(subitmes) for subitems in zip(*items)] for items in zip(x_list, y)]
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