Convert string type array to array
<p>I have  this:</p>

<pre><code>[s[8] = 5,

 s[4] = 3,

 s[19] = 2,

 s[17] = 8,

 s[16] = 8,

 s[2] = 8,

 s[9] = 7,

 s[1] = 2,

 s[3] = 9,

 s[15] = 7,

 s[11] = 0,

 s[10] = 9,

 s[12] = 3,

 s[18] = 1,

 s[0] = 4,

 s[14] = 5,

 s[7] = 4,

 s[6] = 2,

 s[5] = 7,

 s[13] = 9]
</code></pre>

<p>How can I turn this into a python array where I can do <code>for items in x:</code> ?</p>

<p>If you want the array to have the same name that is in the input string, you could use exec. This is not very pythonic, but it works for simple stuff</p>

<pre><code>string = ("[s[8] = 5, s[4] = 3, s[19] = 2,"
   "s[17] = 8, s[16] = 8, s[2] = 8,"
   "s[9] = 7,  s[1] = 2,  s[3] = 9,"
   "s[15] = 7, s[11] = 0, s[10] = 9,"
   "s[12] = 3, s[18] = 1, s[0] = 4,"
   "s[14] = 5, s[7] = 4,  s[6] = 2,"
   "s[5] = 7, s[13] = 9]")

items = [item.rstrip().lstrip() for item in string[1:-1].split(",")]
name = items[0].partition("[")[0]
# Create the array
exec("{} = [None] * {}".format(name, len(items)))
# Populate with the values of the string
for item in items:
    exec(items[0].partition("[")[0] )
</code></pre>

<p>This will generate an array named "s" and if there is an index missing it will be initialized as None</p>

python python-2.7