Transform a numeric string into a list of python numbers

Asked

Viewed 232 times

-2

I need to turn an entry into a list.

The entry has the following form:

['[11, 14]', '[8, 17, 18, 24, 29, 37, 44, 49, 51, 55, 62, 63, 64, 76, 82, 84, 93, 97]']

is read from a file csv. Note that it is composed of two strings, the first '[11, 14]'; and the second '[8, 17, 18, 24, 29, 37, 44, 49, 51, 55, 62, 63, 64, 76, 82, 84, 93, 97]'.

The output I need is a list of integers:

[11, 14, 8, 17, 18, 24, 29, 37, 44, 49, 51, 55, 62, 63, 64, 76, 82, 84, 93, 97]

I searched here on the forum and google, even found some similar tips, I did not succeed.

4 answers

4

You can work with JSON, since the values you have are sequences in JSON as well.

>>> json.loads('[1, 2, 3]')  # [1, 2, 3]

And, to join the lists, you can use the function itertools.chain.from_iterable:

>>> itertools.chain([1, 2, 3], [4, 5, 6])  # [1, 2, 3, 4, 5, 6]

Thus, getting:

import json
import itertools

linha = ['[11, 14]', '[8, 17, 18, 24, 29, 37, 44, 49, 51, 55, 62, 63, 64, 76, 82, 84, 93, 97]']
resultado = list(itertools.chain.from_iterable(json.loads(item) for item in linha))

print(resultado)

See working on Repl.it

2

entrada = ['[11, 14]', '[8, 17, 18, 24, 29, 37, 44, 49, 51, 55, 62, 63, 64, 76, 82, 84, 93, 97]']

saida = []
for string in entrada:
    #tiro o '[' e o ']' e depois separo pelas virgulas. Isso me retorna uma lista com strings
    lista_strings = string.replace('[','').replace(']','').split(',')
    #Transformo as strings da lista em inteiros
    lista_inteiros = [int(i) for i in lista_strings]
    saida.append(lista_inteiros)

>>> print(saida)
[[11, 14], [8, 17, 18, 24, 29, 37, 44, 49, 51, 55, 62, 63, 64, 76, 82, 84, 93, 97]]

0

a = ['[11, 14]', '[8, 17, 18, 24, 29, 37, 44, 49, 51, 55, 82, 84, 93, 97]']

Using lists in understanding we can:

b=[eval(x) for x in a]   ## [[11, 14], [8, 17, 18, 2...]]

To get the single list we have several hypotheses:

c=sum(b,[])

or

c=[y for x in a for y in eval(x)]

(eval(...) can raise safety problems if for example a is being read interactively. For uncontrolled inputs use ast.literal_eval() instead of eval)

  • 1

    Prefer to use ast.literal_eval instead of eval in these situations.

  • @Andersoncarloswoss, Thank you. I don’t know the literal_eval: What is the difference between the two?

  • Is self-explanatory, on the Docs has more information. But in short the eval interprets any python command while ast.literal_eval only literal values such as strings, integers, tuples, lists, etc.. This ensures that no command will be executed from the evaluated string.

  • @Andersoncarloswoss, thank you. Good idea!

0

Well, when using the channel I was not only waiting for help, I was searching from the moment of posting and I was able to solve in the following way:

import re

lista = ['[11, 14]', '[8, 17, 18, 24, 29, 37, 44, 49, 51, 55, 62, 63, 64, 76, 82, 84, 93, 97]']

listalimpa = []

for dado in lista:
    #Divido as string '[11, 14]' e '[8, 17, 18, 24, 29, 37, 44, 49, 51, 55, 62, 63, 64, 76, 82, 84, 93, 97]' faço uma divisão 
    for x in dado.split(','):
    #aqui substituo os caracteres indesejados por nada usando o método sub, do módulo re
        listalimpa.append(int(re.sub('\[|\]|,|''\s*', "", x)))
print(listalimpa)

The exit was as expected:

[11, 14, 8, 17, 18, 24, 29, 37, 44, 49, 51, 55, 62, 63, 64, 76, 82, 84, 93, 97]

Well, and as I commented in the original post, the answer wasn’t the hardest.

Browser other questions tagged

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