How to transform a list that will be given at the input into a matrix?

Asked

Viewed 104 times

0

I’m trying to turn this list that was given to me at the entrance into a matrix

u l i o a

e a p b e

a r y l s

j i t u a

e e h u b

e u o r r

c t n e p

b i o s b

This is one of the input examples, my

But the most I’ve gotten so far is this, which reads only the first line

l = input().split()

diagrama_entrada = []

diagrama_entrada.append(l)
  • 2

    You’ve studied looping ties?

1 answer

0

It is possible to accomplish this using list comprehension in python.

I’m going to use a hypothetical example for believing it will facilitate your understanding:

let’s imagine the following list:

lista = [1,2,3,4,5,6,7,8,9]

And let us imagine now that we seek the following result:

lista_2 = [[1,2,3],[4,5,6],[7,8,9]]

To list_2, a list of lists, also represents a matrix, since:

lista_2[0][0] = 1
lista_2[1][0] = 4
lista_2[2][2] = 9

And so on and so forth...

There are great materials on the internet that unravel this subject, but to simplify your work, note the code below:

# Definimos aqui a lista de entrada
lista = [1,2,3,4,5,6,7,8,9]

# Definimos aqui o tamanho das linhas da matriz
size = 3

# Geramos a lista_2
lista_2 = [x[i:i+size] for i in range(0, len(lista), size)]

And the last line is the following:

The range(0, len(lista), size) creates us a list which will start at zero, end at 9 (length of our list), but its count will be 3 and 3 (our size).

The x[i:i+size] is making a match of our list, ie by cutting it from i to i+size. If I go 0, she’ll cut from 0 to 3, if I go 1, she’ll cut from 1 to 4 and so on.

In the middle of all this time a for loop, which will generate an i (your right) for each term in the list you passed(the range, your left).

Soon, our for loop will run through all the terms of [0, 3, 6] (list generated by the range)and for each of the terms will slice our entry list, getting [i[0:3], i[3:6], i[6:9]], which by their sequence are:

i[0:3] = [1, 2, 3]
i[3:6] = [4, 5, 6]
i[6:9] = [7, 8, 9]

If you want to go deeper I suggest you read about working with lists and then about understanding containers.

Browser other questions tagged

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