我有这个字符串:
'(+ (- 5 4) (- 2 1))'
我希望它将它转换为数组/列表,以便字符串的输出如下:
['+', ['-', 5, 4], ['-', 2, 1]]
括号将是数组内的新数组作为元素。这对我来说有点棘手,因为我刚接触这个。提前谢谢!
编辑:
如果我尝试
'(+ 1 (+ 2 (+ 4 5)))'
输出应为
['+', 1, ['+', 2, ['+', 4, 5]]]
答案 0 :(得分:0)
def interprettokens(tokens):
ans = () # use a tuple at first so we don't get mutability problems.
tokens = (tokens[0][1:],) + tokens[1:-1] + (tokens[-1][:-1],)
while tokens != tuple():
if tokens[0][0] != '(':
ans += (tokens[0],)
tokens = tokens[1:]
else:
if tokens[0][-1] == ')':
ans += ([tokens[0][1:-1]],)
tokens = tokens[1:]
else:
openParenCount = 1
closeParenCount = 0
index = 1
while openParenCount != closeParenCount:
if tokens[index][0] == '(':
openParenCount += 1
if tokens[index][-1] == ')':
closeParenCount += 1
index += 1
ans += (interprettokens(tokens[0:index]),)
tokens = tokens[index:]
return list(ans)
def interpret(string):
tokens = tuple(string.split(' '))
return interprettokens(tokens)
它有点长,但它确实有效。例如,运行interpret('(+ (- 5 4) (- 2 1))')
,它应该可以运行。
答案 1 :(得分:-1)
您可以使用re.split()
将字符串拆分为(
或)
,然后再用空格(i.split()
)拆分结果:
>>> import re
>>> new=[i.split() if re.search(r'\d',i) else i for i in [j for j in re.split(r'\(|\)',s)
>>> [[int(i) if i.isdigit() else i for i in j] if isinstance(j,list) else j for j in new]
['+ ', ['-', 5, 4], ['-', 2, 1]]
演示:
>>> re.split(r'\(|\)',s)
['', '+ ', '- 5 4', ' ', '- 2 1', '', '']
>>>new= [i.split() if re.search(r'\d',i) else i for i in [j for j in re.split(r'\(|\)',s) if len(j.strip())]]
['+ ', ['-', '5', '4'], ['-', '2', '1']]
>>> [[int(i) if i.isdigit() else i for i in j] if isinstance(j,list) else j for j in new]
['+ ', ['-', 5, 4], ['-', 2, 1]]
i.strip()
是因为拒绝选择空间!