如何解析字符串并返回一个嵌套数组? [英] How to parse a string and return a nested array?
本文介绍了如何解析字符串并返回一个嵌套数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想一个Python函数,它接受一个字符串,并返回一个数组,数组中的每个项目可以是一个字符,或者这样的另一个数组。嵌套数组通过与开始(和结尾)标识的输入字符串
因此,该功能将像这样的:
1)富(ABC)== [A,B,C]
2)富(A(B)C)== [一,[B],C]
3)富(A(B(C)))== [一,[B,[C]]]
4)富(A(B(三))==错误:右括号丢失
5)富(A(B))C)==错误:开括号缺失
6)富(A)B(C)==错误:开括号缺失
请注意:我想preFER一个解决方案,这是纯粹的功能
解决方案
高清富(S):
高清foo_helper(级别= 0):
尝试:
令牌=下一个(令牌)
除了StopIteration异常:
如果级别= 0!
引发异常('缺少一个右括号')
其他:
返回[]
如果令牌==')':
如果一级== 0:
引发异常('缺少的开始括号')
其他:
返回[]
ELIF令牌=='(':
返回[foo_helper(等级+ 1)] + foo_helper(水平)
其他:
返回[令牌] + foo_helper(水平)
令牌= ITER(S)
返回foo_helper()
和
>>>美孚('A((B(C))D)(E))
['一',['B',['C'],D],['E']
I want a Python function that takes a string, and returns an array, where each item in the array is either a character, or another array of this kind. Nested arrays are marked in the input string by starting with '(' and ending with ')'.
Thus, the function would act like this:
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
Note: I'd prefer a solution that's purely functional.
解决方案
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()
And,
>>> foo('a((b(c))d)(e)')
['a', [['b', ['c']], 'd'], ['e']]
这篇关于如何解析字符串并返回一个嵌套数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文