How to extract a list from a string in a list in python

Question:

I read a list of lists from a txt file and I got a list like this:

["[21049090, 'AARTIIND22AUGFUT', 'AARTIIND', 850, 1793]", "[21049346, 'ABB22AUGFUT', 'ABB', 250, 3329]"]

Each list item in this list is a str type which is a problem.

it should be like this:

[[21049090, 'AARTIIND22AUGFUT', 'AARTIIND', 850, 1793], [21049346, 'ABB22AUGFUT', 'ABB', 250, 3329]]

How do I do that?

Asked By: KawaiKx

||

Answers:

Consider using literal_eval:

from ast import literal_eval

txt = ["[21049090, 'AARTIIND22AUGFUT', 'AARTIIND', 850, 1793]", "[21049346, 'ABB22AUGFUT', 'ABB', 250, 3329]"]

result = [literal_eval(i) for i in txt]

print(result)

Output:

[[21049090, 'AARTIIND22AUGFUT', 'AARTIIND', 850, 1793], [21049346, 'ABB22AUGFUT', 'ABB', 250, 3329]]

Edit:

Or eval(). Refer to Tim Biegeleisen’s answer.

Answered By: Jeffrey Ram

Using the eval() function along with a list comprehension we can try:

inp = ["[21049090, 'AARTIIND22AUGFUT', 'AARTIIND', 850, 1793]", "[21049346, 'ABB22AUGFUT', 'ABB', 250, 3329]"]
output = [eval(x) for x in inp]
print(output)

This prints:

[
    [21049090, 'AARTIIND22AUGFUT', 'AARTIIND', 850, 1793],
    [21049346, 'ABB22AUGFUT', 'ABB', 250, 3329]
]
Answered By: Tim Biegeleisen

Here is how I will solve it.

from typing import List

def integer_converter(var: str):
    try: 
    # I used float here in case you have any float in those strs
    return float(var)
    except ValueError:
    # if ValueError, then var is a str and cannot be converted. in this case, return str var
    return var

def clear_input(raw_input: List[str]) -> List:
    raw_input = [x.replace('[','').replace(']','').replace("'",'').replace(' ','').split(',') for x in raw_input]
    raw_input = [[integer_converter(x) for x in sublist] for sublist in raw_input]
    return raw_input

test = ["[21049090, 'AARTIIND22AUGFUT', 'AARTIIND', 850, 1793]", "[21049346, 'ABB22AUGFUT', 'ABB', 250, 3329]"]
test = clear_input(test)
print(test)
Answered By: Vae Jiang
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.