2

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!

Ahmed
  • 292
  • 1
  • 7
  • 15

3 Answers3

2

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.

cs95
  • 379,657
  • 97
  • 704
  • 746
  • I accepted this answer versus the one proposed by khelwood (his solution did also solve my problem) because my full code already uses the json library. – Ahmed Jun 13 '17 at 19:23
1

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]]
khelwood
  • 55,782
  • 14
  • 81
  • 108
1

You can use eval to evaluate strings as code.

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