Python中嵌套列表的总和

Jin*_*Jin 7 python list python-3.3

我尝试总结嵌套元素的列表

例如,数字= [1,3,5,6,[7,8]],总和= 30

我写了以下代码

def nested_sum(L):
    sum=0
    for i in range(len(L)):
       if (len(L[i])>1):
          sum=sum+nested_sum(L[i])
       else:
          sum=sum+L[i]
    return sum
Run Code Online (Sandbox Code Playgroud)

上面的代码给出了以下错误:'int'类型的对象没有len()我也试过len([L [i]]),仍然无法正常工作

有人可以帮忙吗?顺便说一下,它是Python 3.3

Vol*_*ity 26

您需要使用isinstance来检查元素是否是列表.此外,您可能希望迭代实际列表,以使事情更简单.

def nested_sum(L):
    total = 0  # don't use `sum` as a variable name
    for i in L:
        if isinstance(i, list):  # checks if `i` is a list
            total += nested_sum(i)
        else:
            total += i
    return total
Run Code Online (Sandbox Code Playgroud)


小智 5

具有列表理解的另一种解决方案:

>>> sum( sum(x) if isinstance(x, list) else x for x in L )
30
Run Code Online (Sandbox Code Playgroud)

编辑:对于超过两个级别的列表(thx @Volatility):

def nested_sum(L):
    return sum( nested_sum(x) if isinstance(x, list) else x for x in L )
Run Code Online (Sandbox Code Playgroud)


Jai*_*ime 5

通常认为鸭子类型更加pythonic ,而不是显式类型检查.像这样的东西将采用任何可迭代的,而不仅仅是列表:

def nested_sum(a) :
    total = 0
    for item in a :
        try:
            total += item
        except TypeError:
            total += nested_sum(item)
    return total
Run Code Online (Sandbox Code Playgroud)


dan*_*lmo 5

我会总结扁平化的列表:

def flatten(L):
    '''Flattens nested lists or tuples with non-string items'''
    for item in L:
        try:
            for i in flatten(item):
                yield i
        except TypeError:
            yield item


>>> sum(flatten([1,3,5,6,[7,8]]))
30
Run Code Online (Sandbox Code Playgroud)