如何将字符串转换为嵌套列表,并用逗号分隔元素

Edg*_*yan 2 python string function list python-3.x

我有一个看起来像这样的字符串:

'(a (b (c d e f)) g)'
Run Code Online (Sandbox Code Playgroud)

我想把它变成这样的嵌套列表:

['a', ['b', ['c', 'd', 'e', 'f']], 'g']
Run Code Online (Sandbox Code Playgroud)

我使用了这个功能:

def tree_to_list(text, left=r'[(]', right=r'[)]', sep=r','):
    pat = r'({}|{}|{})'.format(left, right, sep)
    tokens = re.split(pat, text)    
    stack = [[]]
    for x in tokens:
        if not x or re.match(sep, x): continue
        if re.match(left, x):
            stack[-1].append([])
            stack.append(stack[-1][-1])
        elif re.match(right, x):
            stack.pop()
            if not stack:
                raise ValueError('error: opening bracket is missing')
        else:
            stack[-1].append(x)
    if len(stack) > 1:
        print(stack)
        raise ValueError('error: closing bracket is missing')
    return stack.pop()
Run Code Online (Sandbox Code Playgroud)

但是结果不是我所期望的。字符串之间没有逗号:

['a', ['b', ['c' 'd' 'e' 'f']], 'g']
Run Code Online (Sandbox Code Playgroud)

你能帮我吗

Aja*_*234 5

您可以将递归与生成器一起使用:

import re
data = '(a (b (c d e f)) g)'
def group(d):
    a = next(d, ')')
    if a != ')':
        yield list(group(d)) if a == '(' else a
        yield from group(d)
print(next(group(iter(re.findall(r'\w+|[()]', data)))))
Run Code Online (Sandbox Code Playgroud)

输出:

['a', ['b', ['c', 'd', 'e', 'f']], 'g']
Run Code Online (Sandbox Code Playgroud)