Converting a string to a list of lists
<p>Using Python 2.7, I want to convert a string in the following format to a list of lists:</p>

<pre><code>&gt;&gt;&gt; value = "[[1 0 0 0] [0 1 0 0] [0 0 1 0] [0 0 0 1]]"
&gt;&gt;&gt; ...
&gt;&gt;&gt; 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]]
</code></pre>

<p>I did manage to do just that, but it seems sloppy.</p>

<pre><code>&gt;&gt;&gt; value = "[[1 0 0 0] [0 1 0 0] [0 0 1 0] [0 0 0 1]]"
&gt;&gt;&gt; val2 = value.replace('[[', '').replace(']]', '').split('] [')
&gt;&gt;&gt; val2
['1 0 0 0', '0 1 0 0', '0 0 1 0', '0 0 0 1']
&gt;&gt;&gt; val_final = [[float(x) for x in x] for x in [x.replace(' ', '') for x in val2]]
&gt;&gt;&gt; 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]]
</code></pre>

<p><strong>Is there a better, cleaner way to do this that would be more robust?</strong></p>

<p>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).</p>

<hr>

<p><strong>Edit:</strong>
Alternative value could contain floats like so:</p>

<pre><code>&gt;&gt;&gt; value = "[[9.231 -0.123 -2 0] [0 1 0 0] [0 0 1 0] [0 0 0 1]]"
&gt;&gt;&gt; ...
&gt;&gt;&gt; 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]]
</code></pre>

<p>You can use <code>replace</code> + <code>eval</code>:</p>

<pre><code>value = "[[1 0 0 0] [0 1 0 0] [0 0 1 0] [0 0 0 1]]"
result = eval(value.replace(" ", ","))
result
#output:
[[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 1, 0], [0, 0, 0, 1]]
</code></pre>

<p>And to convert the integers to floats:</p>

<pre><code>[list(map(float, l)) for l in result] #if you're using python 2 you can remove the "list" wrapping the "map" 
#output
[[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]]
</code></pre>

python python-2.7