So I have a list of python formatted like:
x = ['[1,2,3]', '[4,5,6,]', ...]
Is there a way to convert the "inner lists" to actual lists? So the output would be
x = [[1,2,3], [4,5,6], ....]
Thanks!
So I have a list of python formatted like:
x = ['[1,2,3]', '[4,5,6,]', ...]
Is there a way to convert the "inner lists" to actual lists? So the output would be
x = [[1,2,3], [4,5,6], ....]
Thanks!
Another example with json
:
>>> import json
>>> x = ['[1,2,3]', '[4,5,6]']
>>> [json.loads(y) for y in x]
[[1, 2, 3], [4, 5, 6]]
Please limit your strings to dict
s and list
s only.
You can use ast.literal_eval
for this kind of conversion. You can use map
to apply the conversion to each element of your list.
from ast import literal_eval
x = ['[1,2,3]', '[4,5,6,]']
x = map(literal_eval, x)
print x
gives
[[1, 2, 3], [4, 5, 6]]
You can use eval to evaluate strings as code.
x = ['[1,2,3]', '[4,5,6,]']
y = [eval(s) for s in x]