A = [[1,1,1,1],[1,1,1,1]]
B = [[1,1,1,1], [1,1,1,1]]
sum = []
m=len(A[0])
n=len(A)
for i in range(n):
for j in range(m):
sum.append(A[i][j]+B[i][j])
print(sum)
I have result [2,2,2,2,2,2,2,2], but I need [[2,2,2,2],[2,2,2,2]].
A = [[1,1,1,1],[1,1,1,1]]
B = [[1,1,1,1], [1,1,1,1]]
sum = []
m=len(A[0])
n=len(A)
for i in range(n):
for j in range(m):
sum.append(A[i][j]+B[i][j])
print(sum)
I have result [2,2,2,2,2,2,2,2], but I need [[2,2,2,2],[2,2,2,2]].
Consider numpy.
>>> import numpy as np
>>> np.add(A, B)
array([[2, 2, 2, 2],
[2, 2, 2, 2]])
If you don't want to use numpy, consider the following:
>>> [[sum(pair) for pair in zip(sub1, sub2)] for sub1, sub2 in zip(A, B)]
[[2, 2, 2, 2], [2, 2, 2, 2]]
Also do not use sum = [], you will reassign the built in sum function, leading to TypeError: 'list' object is not callable errors.
you can do it easier but about your current code,change it like this:
for i in range(n):
v=[]
for j in range(m):
v.append(A[i][j]+B[i][j])
sum.append(v)
2 and append it to sum. but in my solution, you create a list of 2s, then append that list to sum. and in next iteration of the outer loop, you create an empty list again.@polko