Home > database >  Convert list of strings into list of integers
Convert list of strings into list of integers

Time:06-03

I need to convert a string of 2 items (separated by a comma) to integers.

from:

[['(0,3)', '(1,2)', '(2,2)'], ['(0,3)', '(1,2)', '(2,2)']]

to:

[[(0,3), (1,2), (2,2)], [(0,3), (1,2), (2,2)]]

CodePudding user response:

You can use ast.literal_eval for the task:

from ast import literal_eval

lst = [["(0,3)", "(1,2)", "(2,2)"], ["(0,3)", "(1,2)", "(2,2)"]]

lst = [[literal_eval(v) for v in l] for l in lst]
print(lst)

Prints:

[[(0, 3), (1, 2), (2, 2)], [(0, 3), (1, 2), (2, 2)]]

EDIT: Another approach (thanks @S3DEV):

out = [list(map(literal_eval, sub_list)) for sub_list in lst]

Quick benchmark:

from timeit import timeit
from ast import literal_eval

lst = [["(0,3)", "(1,2)", "(2,2)"], ["(0,3)", "(1,2)", "(2,2)"]]


def fn1():
    return [[literal_eval(v) for v in l] for l in lst]


def fn2():
    return [list(map(literal_eval, sub_list)) for sub_list in lst]


assert fn1() == fn2()

t1 = timeit(lambda: fn1(), number=1_000)
t2 = timeit(lambda: fn2(), number=1_000)

print(t1)
print(t2)

Prints on my machine (AMD 3700X, Python 3.9.7):

0.040873110003303736                                                                                                                                                                                           
0.04002662200946361                                                                                                                                                                                            

CodePudding user response:

If you input always in the pattern.

lst = [['(0,3)', '(1,2)', '(2,2)'], ['(0,3)', '(1,2)', '(2,2)']]

new_lst = list(map(lambda i:[eval(a,{}) for a in i],lst))
# OR

# new_lst = list(map(lambda i:list(map(lambda a:eval(a,{}),i)),lst))
print(new_lst)

OUTPUT

[[(0, 3), (1, 2), (2, 2)], [(0, 3), (1, 2), (2, 2)]]
lst = [['(0,3)', '(1,2)', '(2,2)'], ['(0,3)', '(1,2)', '(2,2)']]
new_lst = []
for a in lst:
    l = []
    for i in a:
        i = i[1:-1].split(',')
        t = []
        for num in i:
            t.append(int(num))
        l.append(tuple(t))

    new_lst.append(l)

print(new_lst)

output

[[(0, 3), (1, 2), (2, 2)], [(0, 3), (1, 2), (2, 2)]]

OR Using Map Function

lst = [['(0,3)', '(1,2)', '(2,2)'], ['(0,3)', '(1,2)', '(2,2)']]

new_lst = [list(map(lambda e:tuple(map(lambda a:int(a),e[1:-1].split(','))),i)) for i in lst]
print(new_lst)
[[(0, 3), (1, 2), (2, 2)], [(0, 3), (1, 2), (2, 2)]]
  • Related