如何用无全局变量的单参数递归方法计算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
相关产品推荐
相关产品推荐

