代码之家  ›  专栏  ›  技术社区  ›  lingyau lee

递归-对嵌套列表求和

  •  0
  • lingyau lee  · 技术社区  · 3 年前

    我试图将嵌套列表中的所有数字相加,作为递归的一种实践。但是,输出结果是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)
    
    1 回复  |  直到 3 年前
        1
  •  1
  •   Freddy Mcloughlan    3 年前

    您将在for循环的第一次迭代中退出。像 i 等于 1 ,然后你输入检查,然后 += total 马上回来。你应该回来 之后 您已退出for循环。

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

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