我有这个:
[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]
如何将其转换为python数组,我可以在其中for items in x:
?
答案 0 :(得分: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]
答案 1 :(得分:2)
如果希望数组与输入字符串中的名称相同,则可以使用exec。这不是非常pythonic,但它适用于简单的东西
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] )
这将生成一个名为“s”的数组,如果缺少一个索引,它将被初始化为None
答案 2 :(得分:1)
假设这是一个巨大的字符串,如果您希望print s[0]
打印4
,那么您需要用逗号分隔它,然后遍历每个项目。
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
答案 3 :(得分:0)
一种简单的方法,虽然效率低于凯文的解决方案(不使用正则表达式),但如下所示(其中some_array
是你的字符串):
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]'])
输出样本:
{'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