如何解析一个字符串并返回一个嵌套数组?
我想要一个Python函数,它接受一个字符串,并返回一个数组,其中数组中的每个项目都是一个字符,或者是另一个这样的数组。嵌套数组在输入字符串中以'('和以')'开头标记。
因此,该函数将如下所示:
1) foo("abc") == ["a", "b", "c"]
2) foo("a(b)c") == ["a", ["b"], "c"]
3) foo("a(b(c))") == ["a", ["b", ["c"]]]
4) foo("a(b(c)") == error: closing bracket is missing
5) foo("a(b))c") == error: opening bracket is missing
6) foo("a)b(c") == error: opening bracket is missing
注意:我更喜欢纯粹功能性的解决方案。
解决方案
def foo(s):
def foo_helper(level=0):
try:
token = next(tokens)
except StopIteration:
if level != 0:
raise Exception('missing closing paren')
else:
return []
if token == ')':
if level == 0:
raise Exception('missing opening paren')
else:
return []
elif token == '(':
return [foo_helper(level+1)] + foo_helper(level)
else:
return [token] + foo_helper(level)
tokens = iter(s)
return foo_helper()
和,
>>> foo('a((b(c))d)(e)')
['a', [['b', ['c']], 'd'], ['e']]
本文首发于Python黑洞网,博客园同步更新