简体   繁体   中英

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

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?

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.

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

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM