How to add elements of one array into the same row in another array?

Viewed 313

I have two arrays that I want to add together by inserting the elements of each row of the first list into the same row in the second list. So instead of converting two 2x3 matrices into one 4x3 matrix, I want to convert them into one 2x6 matrix. I have tried the following, as well as .append and .extend:

test_1 = [[0.0, 0.0, 0.0],[0.0, 0.0, 0.0]]
test_2 = [[1.0, 2.0, 3.0],[4.0, 5.0, 6.0]]
test_3 = test_1 + test_2
print(test_3)

This gives me the output:

[[0.0, 0.0, 0.0], [0.0, 0.0, 0.0], [1.0, 2.0, 3.0], [4.0, 5.0, 6.0]]

However, what I want is:

[[0.0, 0.0, 0.0, 1.0, 2.0, 3.0],[0.0, 0.0, 0.0, 4.0, 5.0, 6.0]]

How do I add the elements of one matrix into the same row on the other matrix?

2 Answers
test_3 = [a+b for a,b in zip(test_1,test_2)]

However, if you're eventually going to convert this to numpy, as most Python matrix processing does, then you will use np.concatenate to do this.

test_1 = [[0.0, 0.0, 0.0],[0.0, 0.0, 0.0]]
test_2 = [[1.0, 2.0, 3.0],[4.0, 5.0, 6.0]]
test_3=[]
for i in range(len(test_1)):
    var=test_1[i]+test_2[i]
    test_3.append(var)
print(test_3)
Related