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

Python不使用导入如何将字符串格式嵌套列表转换为实际列表(递归/迭代)

问题分析

你的代码存在几个核心问题导致无法处理完整输入:

  • 索引计算逻辑错误:递归时传入字符串切片,返回的索引是切片内的相对位置,直接叠加到原字符串的索引上会导致位置计算偏移,嵌套层级越多错误越明显
  • 多位数处理缺失:当前仅能识别单个字符的数字,类似90、120这类多位数会被拆分为多个独立的字符存储,无法转换为完整的整数
  • 可变默认参数陷阱:函数定义时用out=[]作为默认参数,Python会在函数定义时初始化这个列表,多次调用会保留上一次调用的残留值,引发不可预期的错误
  • 字符转整数缺失:当前把数字都存为字符串类型,没有转换为int类型
修复方案(递归实现)

不需要传入切片,直接在原字符串上传递索引即可解决位置计算问题,同时增加多位数拼接逻辑:

s = "[1,[2,3],[4,5,6],[7,[8,90],10],[11,120,[13]]]"

def convert(s, i=0):
    res = []
    num_str = ''
    n = len(s)
    while i < n:
        c = s[i]
        if c == '[':
            # 递归处理子列表,拿到子列表和后续处理的起始索引
            sub_list, i = convert(s, i+1)
            res.append(sub_list)
        elif c == ']':
            # 遇到右括号先完成当前数字的转换存储
            if num_str:
                res.append(int(num_str))
                num_str = ''
            # 返回当前层级的列表和下一个待处理的索引
            return res, i+1
        elif c == ',':
            # 遇到逗号说明当前数字结束,完成转换存储
            if num_str:
                res.append(int(num_str))
                num_str = ''
            i += 1
        else:
            # 拼接数字字符,处理多位数
            num_str += c
            i += 1
    return res, i

result = convert(s)[0]
print(result)

运行后输出和预期结果完全一致:[1, [2, 3], [4, 5, 6], [7, [8, 90], 10], [11, 120, [13]]],全程没有引入任何导入模块。

可选方案(迭代栈实现)

如果要避免递归深度限制,也可以用栈结构实现嵌套处理:

s = "[1,[2,3],[4,5,6],[7,[8,90],10],[11,120,[13]]]"

def convert_iter(s):
    stack = []
    res = None
    num_str = ''
    for c in s:
        if c == '[':
            new_list = []
            if stack:
                stack[-1].append(new_list)
            stack.append(new_list)
        elif c == ']':
            if num_str:
                stack[-1].append(int(num_str))
                num_str = ''
            res = stack.pop()
        elif c == ',':
            if num_str:
                stack[-1].append(int(num_str))
                num_str = ''
        else:
            num_str += c
    return res

print(convert_iter(s))

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.27 04:54:06