简体   繁体   中英

Convert list of strings into list of integers

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

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                                                                                                                                                                                            

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

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