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

Python递归计算嵌套列表深度加权和时结果重置问题求助

递归计算嵌套列表深度加权和的问题

我正在练习递归,已经实现了返回嵌套列表中每个元素的深度(从1开始),但还需要计算嵌套列表的深度加权和(元素值×对应深度的总和)。例如:[1, [4]] → (1×1)+(4×2)=1+8=9。

我用变量res存储总和,但每次进入新的子列表时res都会重置,请问如何像维护output列表一样持续追踪总和?

代码示例

nestedList = [[1,1],2,[1,1]]

def depth_checker(nested_list, depth=1, output=[], res=0):
  for i in nested_list:
    if not isinstance(i, list):
      output.append(depth)
      print(i, depth)
      res = res + (i * depth)
      print(res)
    elif isinstance(i, list):
      depth_checker(i, depth + 1, output, res)
  return (res, output)

当前输出

depth_checker(nestedList)
OUTPUT >>
1 2
2
1 2
4
2 1
2
1 2
4
1 2
6
(2, [2, 2, 1, 2, 2])

期望输出

(10, [2, 2, 1, 2, 2])


解决方案

问题核心:整数是不可变类型,递归调用时传递的是res的副本,子函数内的修改不会影响父函数的res;而列表是可变类型,output的修改会被所有递归层级共享。

方法一:接收递归返回的加权和

让每个递归子函数返回计算后的加权和,父函数接收并更新自身的res:

nestedList = [[1,1],2,[1,1]]

def depth_checker(nested_list, depth=1, output=[], res=0):
  for i in nested_list:
    if not isinstance(i, list):
      output.append(depth)
      res += i * depth
    elif isinstance(i, list):
      # 接收子递归返回的结果,更新当前res
      sub_res, _ = depth_checker(i, depth + 1, output, res)
      res = sub_res
  return (res, output)

print(depth_checker(nestedList))  # 输出 (10, [2, 2, 1, 2, 2])

方法二:用可变对象存储总和

用一个可变容器(比如单元素列表)来保存总和,这样所有递归层级修改的是同一个容器内的值:

nestedList = [[1,1],2,[1,1]]

def depth_checker(nested_list, depth=1, output=[], res=[0]):
  for i in nested_list:
    if not isinstance(i, list):
      output.append(depth)
      res[0] += i * depth
    elif isinstance(i, list):
      depth_checker(i, depth + 1, output, res)
  return (res[0], output)

print(depth_checker(nestedList))  # 输出 (10, [2, 2, 1, 2, 2])

两种方法对比

  • 方法一遵循递归的“返回结果”设计模式,逻辑清晰,可读性强,推荐使用。
  • 方法二利用可变对象特性简化了代码,但需要理解可变/不可变类型的传递差异,适合场景简单的情况。

内容的提问来源于stack exchange,提问作者matt.aurelio

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 03:05:30