多嵌套列表中的整数和浮点数的总和

时间:2016-03-04 02:01:40

标签: python recursion sum

def recListSum(lst):
    '''Takes an arbitrarily nested list as a parameter and returns the sum of
the numbers in the list'''
    if len(lst)==0:
        return 0
    if len(lst) > 0:
        val = recListSum(lst[1:])+recListSum(lst[0])
        if type(lst[0]) != list:
            if type(lst[0])==float or type(lst[0])==int:
                return val
        if type(lst[0])==list and len(lst[0])>0:
            val = recListSum(lst[1:])+recListSum(lst[0])
            return val

3 个答案:

答案 0 :(得分:0)

根据你的评论,听起来你给len()函数一个整数值。由于数字实际上没有长度,因此会产生错误。

我会查看" lst"实际上是一个列表,当你假设它是(在调用这个方法之前可能有一些错误导致" lst"变成一个整数)。

我认为你的最后一个if语句的第一个条件就是保护那里的len()函数,但是如果我没有关于" lst"那么检查它就永远不会受到伤害。有时只是一个整数。

答案 1 :(得分:0)

这是一个可能的解决方案。

def recListSum(lst):
    '''Takes an arbitrarily nested list as a parameter and returns the sum of
the numbers in the list'''
    # handle trivial cases
    if len(lst) == 0:
        return 0
    if len(lst) == 1:
        return lst[0]

    # sum and unfold
    total = 0
    new_lst = []
    for item in lst:
        if isinstance(item, list):
            new_lst += item
        else:
            total += item
    new_lst.append(total)

    # recurse
    return recListSum(new_lst)

答案 2 :(得分:0)

下面列出了一种简单的方法。 我假设lstlist,其中包含listintfloat

def recListSum(lst):
    if type(lst) in (int,float):
        return lst
    elif not type(lst) is list:
        raise TypeError
    elif len(lst) == 0:
        return 0
    else:
        return recListSum(lst[0])+recListSum(lst[1:])
相关问题