2
votes

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!

3

3 Answers

2
votes

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 dicts and lists only.

1
votes

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]]
1
votes

You can use eval to evaluate strings as code.

x = ['[1,2,3]', '[4,5,6,]']
y = [eval(s) for s in x]