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

如何用无全局变量的单参数递归方法计算Python列表的深度

递归计算列表深度的代码修复方案

原代码问题点

  • 未初始化depth变量,直接访问会触发未定义变量报错
  • 递归调用的返回值未接收,每一层递归的局部变量独立,无法跨层级累计深度
  • 函数没有显式return语句,调用后默认返回None

修复思路

仅通过递归返回值传递深度信息,不需要额外参数或全局变量:

  • 边界规则:只要当前输入是列表,基础深度至少为1,空列表直接返回1
  • 遍历所有元素,对列表类型的子元素递归计算深度,记录所有子列表的最大深度
  • 当前列表的总深度 = 子列表最大深度 + 1(当前层的深度计数)

修复后代码

def how_deep(list_of_lists):
    if not list_of_lists:
        return 1
    max_child_depth = 0
    for item in list_of_lists:
        if isinstance(item, list):
            current_depth = how_deep(item)
            if current_depth > max_child_depth:
                max_child_depth = current_depth
    return max_child_depth + 1


if __name__ == '__main__':
    print(how_deep([[[], [], [], [[[]]]], []]))
    print(how_deep([]))
    print(how_deep([[], []]))
    print(how_deep([[[]], [], [[]], [[[]]]]))
    print(how_deep([[[[], [[]], [[[]]], [[[[]]]]]]]))
    print(how_deep([[[], []], [], [[], []]]))

运行输出

6
1
2
5
7
3

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 07:36:10