krm76
krm76

Reputation: 356

How to sum the values from same index from multiple lists within multiple lists?

I have a list that contains multiple lists which 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:

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]])

Upvotes: 0

Views: 111

Answers (1)

Bharel
Bharel

Reputation: 26900

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)]

Upvotes: 1

Related Questions