Home > database >  How to paste 2D Arrays onto each other
How to paste 2D Arrays onto each other

Time:04-13

I'm trying to simply stack two 2D arrays onto each other like this, if I have two 2D arrays like this:

a = [[0, 0],
   [0, 0]]
b = [[1, 1],
   [1, 1]]

I want this output:

ab = [['01', '01'],
     ['01', '01']]

It is important that the final array elements (e.g. 01) are one string and not seperate elements(like ['0','1']). I've been trying with zip and dstack but cannot get it right.

CodePudding user response:

You can do this in a double comprehension list

Edit: Added an int cast to make sure the values don't get interpreted as floats

a = [[0, 0], [0, 0]]
b = [[1, 1], [1, 1]]

result = [[str(int(i))   str(int(j))] for c,d in zip(a,b) for i,j in zip(c,d)]
result = [[result[0][0], result[1][0]], [result[2][0], result[3][0]]]
print result

[['01', '01'], ['01', '01']]

CodePudding user response:

you can try the following if you want the result as strings, otherwise remove the str method

c = [[str(x[0])   str(y[0]), str(x[1])   str(y[1])] for x, y in list(zip(a, b))]

CodePudding user response:

If both 2D arrays always have same size m*n, you can try using this basic nested-looping:

a = [[0, 0],
   [0, 0]]
b = [[1, 1],
   [1, 1]]
c = []
for i in range(len(a)):
    temp = []
    for j in range(len(a[i])):
        temp.append(str(a[i][j]) str(b[i][j]))
    c.append(temp)
  • Related