我希望能够打开字符串,例如:'(* (+ int (+ int real)) int)'
放入嵌套的列表中,括号是列表的开始/结束,如下所示(在本例中)
['*', ['+', 'int', ['+', 'int', 'real']], 'int']
我尝试了以下代码,但它不工作
def bracketCheck(el):
if el == ')' or el == '(':
return False
else:
return True
def stringIntoList(lst):
lst1 = ''
lst2 = []
for i in range(0, len(lst)-1):
if bracketCheck(lst[i]):
lst1 += lst[i]
elif lst[i] == '(':
b = stringIntoList(lst[i:])
elif lst[i] == ')':
lst2.append(lst1)
lst2.append(b)
lst1 = ''
return lst2
您可以让函数跟踪递归调用使用的子字符串的长度:
以便:
退货:
请注意,第一个
[0]
是为了获取列表,因为第二个项目是偏移量,而第二个[0]
是为了获取列表的第一个子列表,因为您显然假设您的输入总是以括号开始和结束。你知道吗相关问题 更多 >
编程相关推荐