递归 - 对嵌套列表求和
我试图将嵌套列表中的所有数字相加,作为递归的练习。但是,输出给出的是 1,而不是所有数字的总和。我哪里做错了?
我尝试循环遍历嵌套列表,如果它是一个列表,那么它会再次调用相同的函数。如果不是列表,则会将数字添加到总数中。
L = [1,2,3,[1, 2, 3],[4, 5, 6],[7, 8, 9]]
def sumL(input):
total = 0
for i in input:
if type(i) is list:
total += sumL(i)
else:
total += i
return total
sumL(L)
I'm trying to sum all the numbers in a nested list as a practice for recursion. However, the output gives 1 instead of the total of all numbers. Where did i go wrong?
I tried looping through the nested list and if its a list, then it calls the same function again. If its not a list, it adds the number to the total.
L = [1,2,3,[1, 2, 3],[4, 5, 6],[7, 8, 9]]
def sumL(input):
total = 0
for i in input:
if type(i) is list:
total += sumL(i)
else:
total += i
return total
sumL(L)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您将在 for 循环的第一次迭代时退出。由于
i
等于1
,然后输入 check it,然后输入+=
total
并立即返回。您应该在退出 for 循环之后返回。注意* 不要使用
input
作为参数,因为它是函数的名称You are exiting on the first iteration of the for loop. As
i
equals1
, then you type check it, then you+=
total
and immediately return. You should return after you have exited the for loop.Note* don't use
input
as an argument, as it is the name of a function