How to parse a string and return a nested array?

前端 未结 7 2156
你的背包
你的背包 2020-11-30 07:48

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 mark

相关标签:
7条回答
  • 2020-11-30 08:50
    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']]
    
    0 讨论(0)
提交回复
热议问题