Arrays in Python - Concatenate

0
Hello, I have two arrays and I would like to concatenate them, ie, put a matrix A and B on the other side of the matrix, in the case of forming a 3x6 matrix, but using a loop ("for" command) for this. can you help me? Thank you.

matriz_a = [
    [0, 0, 1],
    [0, 1, 0],
    [1, 0, 1]
]

print(matriz_a)


matriz_b = [
        [2, 2, 3],
        [3, 2, 2],
        [3, 3, 3]
    ]

print(matriz_b)
    
asked by anonymous 01.06.2018 / 18:23

2 answers

3

You can use the native function zip :

def matrix_union(A, B):
    for a, b in zip(A, B):
        yield [*a, *b]

The function return will be a generator in which each row will be the join of the lines of matrix A with matrix B.

For example:

A = [
    [0, 0, 1],
    [0, 1, 0],
    [1, 0, 1]
]

B = [
    [2, 2, 3],
    [3, 2, 2],
    [3, 3, 3]
]

print(list(matrix_union(A, B)))

See working at Repl.it | Ideone | GitHub GIST

Will generate:

[
    [0, 0, 1, 2, 2, 3], 
    [0, 1, 0, 3, 2, 2], 
    [1, 0, 1, 3, 3, 3]
]
    
01.06.2018 / 19:17
0

You do not even have to use for . You can do the following:

matriz_a = [
    [0, 0, 1],
    [0, 1, 0],
    [1, 0, 1]
]

matriz_b = [
        [2, 2, 3],
        [3, 2, 2],
        [3, 3, 3]
    ]

matriz_c = [*matriz_a, *matriz_b]  
print(matriz_c)
# [[0, 0, 1], [0, 1, 0], [1, 0, 1], [2, 2, 3], [3, 2, 2], [3, 3, 3]]

The operator * unpacks each of its arrays.

If you still want to use a for and no other method, you could do the following:

matriz_c = []

for matriz in (matriz_a, matriz_b):
    for elemento in matriz:
        matriz_c.append(elemento)        

print(matriz_c)
#  [[0, 0, 1], [0, 1, 0], [1, 0, 1], [2, 2, 3], [3, 2, 2], [3, 3, 3]]
    
01.06.2018 / 18:34