How to join 2 lists in a single Matrix?

Asked

Viewed 781 times

0

Make a program that creates two vectors, using lists and, receive 6 integer numbers in each of the vectors. Finally, the program must create a 3x4 matrix from the intercalation of the two vectors.

This intercalation shall take place as follows::

Captures two elements of vector 1 and places them in the matrix

Capture two elements of vector 2 and place in the matrix

Repeat until fill in the matrix

How do I intersperse ?

    vet1 = []
    vet2 = []
    vet3 = []

    print ('Informe os valores do primeiro vetor')

    for i in range(0, 3):
        vet1.append(int(input('Informe um numero: ')))

    print ('Informe os valores do segundo vetor')

    for i in range(0, 3):
        vet2.append(int(input('Informe um numero: ')))

    for i in range(0, 3):
        vet3.append(vet1[i]) 
        vet3.append(vet2[i])

     print (vet3)

this was the code I made to test

  • You have to show what you have already done, if the doubt is the intercalation show the code to create the vectors

  • edited with the code

2 answers

0

can do as follows:

vet1 = []
vet2 = []
vet3 = []

print ('Informe os valores do primeiro vetor')

for i in range(0, 3):
    vet1.append(int(input('Informe um numero: ')))

print ('Informe os valores do segundo vetor')

for i in range(0, 3):
    vet2.append(int(input('Informe um numero: ')))

vet3.append(vet1)
vet3.append(vet2)

print(vet3)

my way out:

adryan@notebook:~/Python$ python3 teste.py 
Informe os valores do primeiro vetor
Informe um numero: 3
Informe um numero: 2
Informe um numero: 4
Informe os valores do segundo vetor
Informe um numero: 5
Informe um numero: 6
Informe um numero: 3
[[3, 2, 4], [5, 6, 3]]

0

I think this code can help you:

def intercalacao(vetor_1=None, vetor_2=None):
    num_linhas = 3
    num_colunas = 4
    # cria matriz 3x4
    matriz = [[0 for i in range(num_colunas)] for j in range(num_linhas)]

    # intercala os valores dos vetores
    # montando assim a matriz 
    for i in range(num_linhas):
        for j in range(num_colunas):
            # j for divisivel por 2
            if j % 2 == 0:
                # remove o primeiro elemento do vetor
                # e a posicao da matriz recebe seu valor
                matriz[i][j] = vet_1.pop(0)
                #
            else:
                matriz[i][j] = vet_2.pop(0)

    return matriz


if __name__ == '__main__':

    vet_1 = [1, 2, 3, 4, 5, 6]
    vet_2 = [7, 8, 9, 10, 11, 12]

    matriz = intercalacao(vetor_1=vet_1, vetor_2=vet_2)
    print(matriz)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.