嵌套列表深度总和python



我正在练习递归,我想为列表的每个元素返回深度(从1开始((我已经完成了(,但也要返回嵌套列表深度的加权和*值。

例如,[1,[4]]->(1*1(+(4*2(=1+8=9

我使用变量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)
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](

您可以这样做:

def depth_checker(nested_list, depth=1):
res = 0
for obj in nested_list:
if isinstance(obj, list):
res += depth_checker(obj, depth + 1)
else:
res += obj * depth
return res

print(depth_checker([2, 2, 1, 2, 2])) # 9

问题在于列表和整数的实现之间的差异。当您对depth_checker进行递归调用时,对output的任何更改都将反映在原始变量中。但是,对res所做的更改不会修改传入的变量。列表是可变的,整数不是。

最简单的选择是在所有情况下更改代码以返回值res。然后将最后一行修改为res = depth_checker(....),以便更新

最新更新