0

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: ?

Moinuddin Quadri
48.4k13 gold badges101 silver badges138 bronze badges
asked Sep 22, 2016 at 18:29
15
  • 1
    What kind of data-structure is that? It has the list brackets around it but contains notation to set key and value in a dict? Commented Sep 22, 2016 at 18:35
  • Are you sure it is the original chunk of code? Commented Sep 22, 2016 at 18:35
  • Is that a string in your code? Commented Sep 22, 2016 at 18:35
  • 3
    Then edit you answer to mentioned it as string. " around each item Commented Sep 22, 2016 at 18:36
  • 3
    What is the expected output? please also mention that Commented Sep 22, 2016 at 18:36

4 Answers 4

4
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]
answered Sep 22, 2016 at 18:47
Sign up to request clarification or add additional context in comments.

Comments

1

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

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

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

answered Sep 22, 2016 at 19:08

Comments

0

Assuming this is one giant string, if you want print s[0] to print 4, then you need to split this up by the commas, then iterate through each item.

inputArray = yourInput[1:-1].replace(' ','').split(',\n\n')
endArray = [0]*20
for item in inputArray:
 endArray[int(item[item.index('[')+1:item.index(']')])]= int(item[item.index('=')+1:])
print endArray
answered Sep 22, 2016 at 18:51

Comments

0

An easy way, although less efficient than Kevin's solution (without using regular expressions), would be the following (where some_array is your string):

sub_list = some_array.split(',')
some_dict = {}
for item in sub_list:
 sanitized_item = item.strip().rstrip().lstrip().replace('=', ':')
 # split item in key val
 k = sanitized_item.split(':')[0].strip()
 v = sanitized_item.split(':')[1].strip()
 if k.startswith('['):
 k = k.replace('[', '')
 if v.endswith(']'):
 v = v.replace(']', '')
 some_dict.update({k: int(v)})
print(some_dict)
print(some_dict['s[9]'])

Output sample:

{'s[5]': 7, 's[16]': 8, 's[0]': 4, 's[9]': 7, 's[2]': 8, 's[3]': 9, 's[10]': 9, 's[15]': 7, 's[6]': 2, 's[7]': 4, 's[14]': 5, 's[19]': 2, 's[17]': 8, 's[4]': 3, 's[12]': 3, 's[11]': 0, 's[13]': 9, 's[18]': 1, 's[1]': 2, 's8]': 5}
7
answered Sep 22, 2016 at 18:55

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.