HEADLESS_0NE - 1 year ago 75
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]]
``````

``````>>> value = "[[1 0 0 0] [0 1 0 0] [0 0 1 0] [0 0 0 1]]"