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

Time:01-08

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

CodePudding user response:

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)]
  •  Tags:  
  • Related