Home > Software engineering >  How to extract a list from a string in a list in python
How to extract a list from a string in a list in python

Time:08-29

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?

CodePudding user response:

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.

CodePudding user response:

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

CodePudding user response:

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)
  • Related