You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过递归将带括号的字符串转换为嵌套列表?

问题描述

需要将字符串 'f(g,h(a,b),a,b(g,h))' 转换为嵌套列表 ['f',['g','h',['a','b'],'a','b',['g','h']]],本质是把字符串里的所有 ( 替换为 [、) 替换为 ],最终得到合法的Python嵌套列表结构。

尝试用递归实现这个逻辑:遍历字符串,遇到 ( 时创建新列表并向其中添加后续元素;遇到 ) 时将当前列表添加到最近的外层列表,但刚接触递归,不知道怎么落地,写出的代码无法正常运行。

尝试的代码
word='f(a,f(a))'
empty=[]
def newlist(word):
    listy=[]
    for i, letter in enumerate(word):
        if letter=='(':
            return newlist([word[i+1:]])
        if letter==')':
            listy.append(newlist)
        else:
            listy.extend(letter)
        
    return empty.append(listy)
递归实现解决方案

你的思路方向是对的,但递归实现时需要跟踪当前处理的位置和当前所在的列表层级,避免用切片反复传递子串(会导致位置丢失),同时要明确递归的终止条件。

下面是可运行的递归实现代码:

def str_to_nested_list(s):
    # 用索引跟踪当前处理位置,避免切片带来的位置混乱
    index = 0
    
    def helper():
        nonlocal index
        current_list = []
        current_item = []
        
        while index < len(s):
            char = s[index]
            index += 1
            
            if char == '(':
                # 遇到左括号,递归处理内部元素,结果作为当前列表的元素
                nested = helper()
                current_list.append(nested)
            elif char == ')':
                # 遇到右括号,先把当前积累的单个字符加入列表,再返回当前列表给上层
                if current_item:
                    current_list.append(''.join(current_item))
                    current_item = []
                return current_list
            elif char == ',':
                # 遇到逗号,把当前积累的单个字符加入列表,清空临时容器
                if current_item:
                    current_list.append(''.join(current_item))
                    current_item = []
            else:
                # 普通字符,先积累到临时容器
                current_item.append(char)
        
        # 遍历结束后,把剩余的临时字符加入列表
        if current_item:
            current_list.append(''.join(current_item))
        return current_list
    
    result = helper()
    # 处理最外层结构:原字符串是"元素(嵌套内容)",需要整合成['元素', [嵌套内容]]
    if len(result) >= 2 and isinstance(result[1], list):
        return [result[0], result[1]]
    return result

# 测试
test_str = 'f(g,h(a,b),a,b(g,h))'
print(str_to_nested_list(test_str))
# 输出:['f', ['g', 'h', ['a', 'b'], 'a', 'b', ['g', 'h']]]

代码说明

  1. 共享索引跟踪:用nonlocal让递归函数共享同一个索引,确保每个字符只被处理一次,不会重复或遗漏。
  2. 临时字符容器:current_item用来积累单个元素(比如f、a),遇到逗号、括号时再将其加入当前列表。
  3. 递归逻辑:遇到(时调用helper()处理括号内的内容,返回的嵌套列表直接作为当前列表的元素;遇到)时结束当前层级递归,把当前列表返回给上层。
  4. 最外层适配:针对原字符串元素(嵌套内容)的结构,最后将最外层元素和嵌套列表整合成目标格式。

如果输入字符串完全可信,也可以用更简单的替换+eval方式实现:

s = 'f(g,h(a,b),a,b(g,h))'
# 替换括号后给最外层加[],再用eval转换为列表
result = eval(f"[{s.replace('(', '[').replace(')', ']')}]")
print(result)
# 输出:['f', ['g', 'h', ['a', 'b'], 'a', 'b', ['g', 'h']]]

这个方法更简洁,但eval存在安全风险,仅适用于可信输入场景,递归方法则更安全可控。

内容的提问来源于stack exchange,提问作者Robert Selangor

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.16 22:01:16