How to separate the letters of a string that are inserted into a list and place them in an array?

Asked

Viewed 5,739 times

5

I have a list with the word "test", arranged in such a way:

['teste','teste','teste','teste','teste']

I would like to turn this list into a matrix, in which the letters are separated from each other:

[
  ['t','e','s','t','e']
  ['t','e','s','t','e']
  ['t','e','s','t','e']
  ['t','e','s','t','e']
  ['t','e','s','t','e']
]

4 answers

11


You can use list() to turn strings into lists. If you do list(string), the result is a list in which each element is a string character. Ex:

print(list('teste'))

This prints:

['t', 'e', s', t', 'e']

So just do this for each element of your list, and go adding these lists in your matrix (where "matrix" is nothing more than a list of lists: a list in which each element is also a list):

lista = ['teste', 'teste', 'teste', 'teste', 'teste']

matriz = [list(palavra) for palavra in lista]
print(matriz)

This prints:

[['t', 'e', s', t', 'e'], [’t', 'e', s', t', 'e'], [’t', 'e', s', t', 'e'], [’t', 'e', s', t', 'e'], [’t', 'e', s', t', 'e']]

Note that I used the syntax of comprehensilist on, which is more succinct and pythonic. The above code is equivalent to:

lista = ['teste', 'teste', 'teste', 'teste', 'teste']

matriz = []
for palavra in lista:
    matriz.append(list(palavra))

print(matriz)
  • 1

    Very cool this answer.

  • 1

    thanks a lot! I spent a lot of time cracking my head with this list function.

2

An easy way to separate letters in a string and allocate them in a list is by using the function list() python. Thus:

palavras = ['teste','teste','teste','teste','teste']
matriz = []

for palavra in palavras:
    matriz.append(list(palavra))

With this, if you have display the contents of the list matriz, the result will be exactly what you expect:

print(matriz)

[['t', 'e', 's', 't', 'e'],
 ['t', 'e', 's', 't', 'e'],
 ['t', 'e', 's', 't', 'e'],
 ['t', 'e', 's', 't', 'e'],
 ['t', 'e', 's', 't', 'e']]

The function list() traverses each position of the object passed as parameter, transforms each of these positions into a new object and allocates within a list. The method .append() adds the given parameter inside the list.

In that case, we turn every word 'teste' on a list ['t','e','s','t','e'] and allocate within the list matriz, which had previously been created.

1

a = ['teste','teste','teste','teste','teste']

b = []

for palavra in a:
    linha = []
    for letra in palavra:
        linha.append(letra)
    b.append(linha)

print(b)

Output:

[['t', 'e', 's', 't', 'e'], ['t', 'e', 's', 't', 'e'], ['t', 'e', 's', 't', 'e'], ['t', 'e', 's', 't', 'e'], ['t', 'e', 's', 't', 'e']]

1

I think I can help you that way using List:

testes = ['teste','teste','teste','teste','teste']
testes_separados = []
for teste in testes:
    testes_separados.append(list(teste))

print(teste)

Browser other questions tagged

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