HEADLESS_0NE HEADLESS_0NE - 1 year ago 63
Python Question

Converting a string to a list of lists

Using Python 2.7, I want to convert a string in the following format to a list of lists:

>>> value = "[[1 0 0 0] [0 1 0 0] [0 0 1 0] [0 0 0 1]]"
>>> ...
>>> result = [[1.0, 0.0, 0.0, 0.0], [0.0, 1.0, 0.0, 0.0], [0.0, 0.0, 1.0, 0.0], [0.0, 0.0, 0.0, 1.0]]


I did manage to do just that, but it seems sloppy.

>>> value = "[[1 0 0 0] [0 1 0 0] [0 0 1 0] [0 0 0 1]]"
>>> val2 = value.replace('[[', '').replace(']]', '').split('] [')
>>> val2
['1 0 0 0', '0 1 0 0', '0 0 1 0', '0 0 0 1']
>>> val_final = [[float(x) for x in x] for x in [x.replace(' ', '') for x in val2]]
>>> val_final
[[1.0, 0.0, 0.0, 0.0], [0.0, 1.0, 0.0, 0.0], [0.0, 0.0, 1.0, 0.0], [0.0, 0.0, 0.0, 1.0]]


Is there a better, cleaner way to do this that would be more robust?

Note: I do expect to only have integer or float values in the string (context: it's a 4x4 matrix corresponding to an object position in a 3D environment).




Edit:
Alternative value could contain floats like so:

>>> value = "[[9.231 -0.123 -2 0] [0 1 0 0] [0 0 1 0] [0 0 0 1]]"
>>> ...
>>> result = [[9.231, -0.123, -2.0, 0.0], [0.0, 1.0, 0.0, 0.0], [0.0, 0.0, 1.0, 0.0], [0.0, 0.0, 0.0, 1.0]]

Answer Source

Use json.dumps from the standard library, with a little bit of preparation (replace spaces with commas):

>>> value = "[[1 0 0 0] [0 1 0 0] [0 0 1 0] [0 0 0 1]]"
>>> result = json.loads(value.replace(' ', ','))
[[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 1, 0], [0, 0, 0, 1]]

That should be safer than eval and easier than manually parsing the string and convert it to the right datatypes, the json parser will do that for you.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download