Reputation:
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:
?
Upvotes: 0
Views: 123
Reputation: 11
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
Upvotes: 1
Reputation: 3536
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
Upvotes: 0
Reputation: 658
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
Upvotes: 0
Reputation: 76194
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]
Upvotes: 4