2

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]

c=[]
for l in b:
    n=[]
    for x in l:
        n.append(float(x))
    c.append(n)

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

0

1 Answer 1

10
>>> 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

Sign up to request clarification or add additional context in comments.

1 Comment

Perfect, I can't believe I've never seen these in use before

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.