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]]"
c = [[1,2,3],[4,5,6],[7,8,9]]
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]
c=[]
for l in b:
n=[]
for x in l:
n.append(float(x))
c.append(n)
>>> 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