user3062260 user3062260 - 1 year ago 59
Python Question

python convert string of lists into a list of lists

I am looking for an elegant way to convert a string into a list of lists. I am reading them from a text file so can't alter the format that i receive the string in. Here as an example string:

a = "[[1,2,3],[4,5,6],[7,8,9]]"

I would like to convert it into something like this:

c = [[1,2,3],[4,5,6],[7,8,9]]

The only way I can think to do this is a bit clunky involving several steps using .split() and .replace()

b = a.split('],[')
for i in range(len(b)):
b[i] = b[i].replace('[','')
b[i] = b[i].replace(']','')

b=[[x] for x in b]
b = [float(x[0].split(',')) for x in b]

for l in b:
for x in l:

whilst this works, its repulsive and clunky. If anyone knows of an elegant way of doing this please let me know. Many thanks

>>> import json
>>> json.loads("[[1,2,3],[4,5,6],[7,8,9]]")
[[1, 2, 3], [4, 5, 6], [7, 8, 9]]

İt's way easy :)

>>> a = "[[1,2,3],[4,5,6],[7,8,9]]"
>>> import ast
>>> m=ast.literal_eval(a)
>>> m
[[1, 2, 3], [4, 5, 6], [7, 8, 9]]

Also this works