John McKean John McKean - 2 months ago 7
Python Question

Convert string type array to array

I have this:

[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]


How can I turn this into a python array where I can do
for items in x:
?

Answer
import re

data = """[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]"""

d = {int(m.group(1)): int(m.group(2)) for m in re.finditer(r"s\[(\d*)\] = (\d*)", data)}
seq = [d.get(x) for x in range(max(d))]
print(seq)
#result: [4, 2, 8, 9, 3, 7, 2, 4, 5, 7, 9, 0, 3, 9, 5, 7, 8, 8, 1]
Comments