Matrix generator in Python

Asked

Viewed 3,471 times

0

The program does the following: I say the number of rows and columns I want in my matrix and then assign a value to each column in each row, the problem is that when I specify the number of rows through the append() it creates a "fake list"by placing the elements of the first sub-list in all other:

lista = []
linha = []
nc = int(input('Quantas colunas? '))
nl = int(input('Quantas linhas? '))
for c in range(0, nl):
    lista.append(linha)
for c1 in range(0, nl):
    for c2 in range(0, nc):
        n = int(input(f'Número L[{c1+1}] C[{c2+1}]: '))
        lista[c1].append(n)
print(lista)

And in case I try to put lista[c1][c2] he makes the following mistake:

`lista[c1][c2].append(n)`
> zIndexError: list index out of range`

Output:
Quantas colunas? 3
Quantas linhas? 3 
Número L[1] C[1]: 1
Número L[1] C[2]: 2 
Número L[1] C[3]: 3
Número L[2] C[1]: 4 
Número L[2] C[2]: 5
Número L[2] C[3]: 6 
Número L[3] C[1]: 7 
Número L[3] C[2]: 8 
Número L[3] C[3]: 9 
[[1, 2, 3, 4, 5, 6, 7, 8, 9], [1, 2, 3, 4, 5, 6, 7, 8, 9], [1, 2, 3, 4, 5, 6, 7, 8, 9]]

`

Now when I leave set the amount of lines

lista = [[], [], []]
for c1 in range(0, 3):
    for c2 in range(0, 3):
        n = int(input(f'Número L[{c1+1}] C[{c2+1}]: '))
        lista[c1].append(n)
print(lista)

it adds the numbers at the correct positions:

Número L[1] C[1]: 1
Número L[1] C[2]: 2
Número L[1] C[3]: 3
Número L[2] C[1]: 4
Número L[2] C[2]: 5
Número L[2] C[3]: 6
Número L[3] C[1]: 7
Número L[3] C[2]: 8
Número L[3] C[3]: 9
[[1, 2, 3], [4, 5, 6], [7, 8, 9]]

I really appreciate you guys helping me out!

4 answers

4

The problem is that in your bond you create one list and assign it to the row variable - and then, you assign that same list to each position in your matrix.

If you create a new list on each line, it will already work:

lista = []
nc = int(input('Quantas colunas? '))
nl = int(input('Quantas linhas? '))
for c in range(0, nl):
    lista.append([])
...

Okay, with that, in every interaction of c, a new list is created (when Python finds the expression [] - could also be a call to list(): same).)

  • Thanks, I thought I couldn’t put [ ] in parentheses that he would accept as a list...

  • @Andrepaganotto Don’t forget to mark the answer as accepted if it solved the problem

0

One of the correct ways to assemble a two-dimensional matrix in python is by using the algorithm shown below. Note also that in this algorithm I used the library numpy which must be installed beforehand.

import numpy as np

m = int(input('Quantas linas? '))
n = int(input('Quantas colunas? '))

matrizA = list()
for c in range(1, m + 1):
    linha = list()
    for i in range(1, n + 1):
        while True:
            try:
                valor = int(input(f'Digite o {i}º elemento da {c}ª linha: '))
                break
            except ValueError:
                print('\033[31mValor INVÁLIDO! Digite apenas valores inteiros!\033[m')
        linha.append(valor)
    matrizA.append(linha)

matriz = np.array(matrizA)
print(f'\033[32mA matriz gerada é:\n{matriz}\033[m')

Note that when we run the algorithm we receive the first message; Quantas linhas?. At this point we must enter the number of rows of the matrix and press enter. Later we received the second message; Quantas colunas?. At this point we must type the amount of columns and press enter.

After that, we got the message; Digite o 1º elemento da 1ª linha: . At this point we must enter the value of the element that corresponds to the intersection of the first line with the first column. Then we must enter the other values.

Observing

It is good to note that the second for traverse the range representing the number of columns and, for each interaction, insert the value captured by input block while on the list "linha". After the list "linha" is complete (according to the number of columns previously passed), the first time insert the list "linha" on the list "matrizA".

This process is redone until the list "matrizA" be complete.

Once the list "matrizA" is complete, shall be subjected to the array library numpy, being converted into a matrix (array) two-dimensional and then displayed.

0

The matrix is being created in the wrong way it should be created like this:

lista = []
linha = []
nc = int(input('Quantas colunas? '))
nl = int(input('Quantas linhas? '))
for c1 in range(0, nl):
    linha = []
    for c2 in range(0, nc):
        n = int(input('Número L[{0}] C[{1}]: '.format(c1 + 1,c2 + 1)))
        linha.append(n)
    lista.append(linha)
print(lista)

But why ?

Because so the columns (the number of each) already go straight to your lines preventing any kind of error.

-1

import random

lista = []
linha = []
nc = int(input('Quantas colunas? '))
nl = int(input('Quantas linhas? '))

for i in range(nl):
    for i in range(nc):
        randomNum = random.randrange(-5,5,1)
        linha.append(randomNum)
    lista.append(linha)
    linha = []
for k in lista:
    print (k)

Browser other questions tagged

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