递归 - 对嵌套列表求和

发布于 2025-01-17 11:52:48 字数 377 浏览 1 评论 0原文

我试图将嵌套列表中的所有数字相加,作为递归的练习。但是,输出给出的是 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

故笙诉离歌 2025-01-24 11:52:48

您将在 for 循环的第一次迭代时退出。由于 i 等于 1,然后输入 check it,然后输入 += total 并立即返回。您应该在退出 for 循环之后返回。

def sumL(ls):
    total = 0
    for i in ls:
        if isinstance(i, list):
            total += sumL(i)
        else:
            total += i
    return total

注意* 不要使用 input 作为参数,因为它是函数的名称

You are exiting on the first iteration of the for loop. As i equals 1, then you type check it, then you += total and immediately return. You should return after you have exited the for loop.

def sumL(ls):
    total = 0
    for i in ls:
        if isinstance(i, list):
            total += sumL(i)
        else:
            total += i
    return total

Note* don't use input as an argument, as it is the name of a function

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文