I have a list of strings and those strings are lists. Like this: [\'[1,2,3]\',\'[10,12,5]\']
, for example. I want to get a list of lists or even every list there: <
You can use ast.literal_eval
, eval
should generally be avoided:
l= ['[1,2,3]','[10,12,5]']
from ast import literal_eval
print([literal_eval(ele) for ele in l])
[[1, 2, 3], [10, 12, 5]]
Or index, split and map:
print([list(map(int,ele[1:-1].split(","))) for ele in l])
[[1, 2, 3], [10, 12, 5]]
If you always have the same format splitting is the most efficient solution:
In [44]: %%timeit
l= ['[1,2,3]','[10,12,5]']
l = [choice(l) for _ in range(1000)]
[eval(ele) for ele in l]
....:
100 loops, best of 3: 8.15 ms per loop
In [45]: %%timeit
l= ['[1,2,3]','[10,12,5]']
l = [choice(l) for _ in range(1000)]
[literal_eval(ele) for ele in l]
....:
100 loops, best of 3: 11.4 ms per loop
In [46]: %%timeit
l= ['[1,2,3]','[10,12,5]']
l = [choice(l) for _ in range(1000)]
[list(map(int,ele[1:-1].split(","))) for ele in l]
....:
100 loops, best of 3: 2.07 ms per loop