Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

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                                                                                                                                                                                            
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading