How to transform a list that will be given on entry into an array?

0

I'm trying to transform this list that was given to me in input into an array

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 achieved so far is this, which reads only the first line

l = input().split()

diagrama_entrada = []

diagrama_entrada.append(l)
    
asked by anonymous 29.05.2018 / 19:53

1 answer

0

You can do this using list understanding in python.

I will use a hypothetical example because I believe it will make it easier to understand:

let's imagine the following list:

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

And now imagine that we are looking for the following result:

lista_2 = [[1,2,3],[4,5,6],[7,8,9]]
The list_2 , a list of lists, also represents an array , since:

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

And so on ...

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)]

Being that the last line happens the following:

The range(0, len(lista), size) creates a list that will start at zero, finish at 9 (length of our list), but its count will be 3 and 3 (our size) p>

x[i:i+size] is making a slice from our list, ie by cutting it from i to i + size. If i is 0, it will cut from 0 to 3, if i is 1, it will cut from 1 to 4 and so on.

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

So, our for loop will run all terms of [0, 3, 6] ( list generated by the range) and for each of the terms it will slice our input 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 reading about working with lists and then understanding containers.

    
29.05.2018 / 21:17