-3

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?

KawaiKx
  • 9,558
  • 19
  • 72
  • 111
  • @TheFungusAmongUs Consider changing the link you've provided to this: [Do not use signature, taglines, greetings, thanks, or other chitchat.](https://stackoverflow.com/help/behavior) because the one you've provided is irrelevant to the issue you've raised. – Jeffrey Ram Aug 29 '22 at 02:32

3 Answers3

1

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.

Jeffrey Ram
  • 1,132
  • 1
  • 10
  • 16
0

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]
]
Tim Biegeleisen
  • 502,043
  • 27
  • 286
  • 360
0

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)
Vae Jiang
  • 337
  • 3
  • 8
  • This solution does not work with `["[21049090, 'AARTIIND22AUGFUT', 'AARTIIND', 850, 1793]", "[21049346, 'ABB22AUGFUT', 'ABB', 250, 3329]"]` – Jeffrey Ram Aug 29 '22 at 02:29
  • @JeffreyRam, you are right. I modified my answer, and it should now work for the direct read from a file. – Vae Jiang Aug 29 '22 at 02:48