11

我尝试总结嵌套元素列表

例如,numbers=[1,3,5,6,[7,8]]应该产生sum=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

上面的代码给出了以下错误:

'int' 类型的对象没有 len()

我也试过了len([L[i]]),还是不行。

任何人都可以帮忙吗?它是 Python 3.3

4

14 回答 14

30

您需要使用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
于 2013-02-17T01:29:07.293 回答
6

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

def nested_sum(a) :
    total = 0
    for item in a :
        try:
            total += item
        except TypeError:
            total += nested_sum(item)
    return total
于 2013-02-17T06:37:52.290 回答
5

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

>>> sum( sum(x) if isinstance(x, list) else x for x in L )
30

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

def nested_sum(L):
    return sum( nested_sum(x) if isinstance(x, list) else x for x in L )
于 2013-02-17T01:41:15.783 回答
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
于 2013-07-09T23:01:36.160 回答
4

使用 lambda 处理嵌套列表的快速递归:

rec = lambda x: sum(map(rec, x)) if isinstance(x, list) else x

rec,应用于列表,将返回总和(递归),在一个值上,返回该值。

result = rec(a)
于 2014-03-20T14:44:26.403 回答
1

使用过滤器和映射以及递归的示例:

def islist(x): 
    return isinstance(x, list)

def notlist(x): 
    return not isinstance(x, list)

def nested_sum(seq):
    return sum(filter(notlist, seq)) + map(nested_sum, filter(islist, seq))

这是一个使用reduce和recursion的例子

from functools import reduce


def nested_sum(seq):
    return reduce(lambda a,b: a+(nested_sum(b) if isinstance(b, list) else b), seq)

使用普通旧递归的示例:

def nested_sum(seq):
    if isinstance(seq[0], list):
        head = nested_sum(seq[0])
    else:
        head = seq[0]
    return head + nested_sum(seq[1:])

使用模拟递归的示例:

def nested_sum(seq):
    stack = []
    stack.append(seq)
    result = 0
    while stack:
        item = stack.pop()
        if isinstance(item, list):
            for e in item:
                stack.append(e)
        else:
            result += item
    return result

处理自引用列表的调整留给读者作为练习。

于 2013-12-20T06:07:48.577 回答
1

此代码也有效。

def add_all(t):
    total = 0
    for i in t:
        if type(i) == list: # check whether i is list or not
            total = total + add_all(i)
        else:
            total += i
    return total
于 2015-03-27T11:13:29.497 回答
1
 def sum_nest_lst(lst):
         t=0
         for l in lst:
             if(type(l)==int):
                 t=t+l
             if(type(l)==list):
                 t=t+sum(l)
         print(t)
于 2020-11-02T03:53:48.720 回答
0
def nnl(nl): # non nested list function

    nn = []

    for x in nl:
        if type(x) == type(5):
            nn.append(x)

        if type(x) == type([]):
            n = nnl(x)

        for y in n:
            nn.append(y)

     return sum(nn)


 print(nnl([[9, 4, 5], [3, 8,[5]], 6])) # output:[9,4,5,3,8,5,6]

 a = sum(nnl([[9, 4, 5], [3, 8,[5]], 6]))
 print (a) # output: 40
于 2018-08-24T14:35:51.563 回答
0

一个简单的解决方案是使用嵌套循环。

def nested_sum(t):

    sum=0
    for i in t:
        if isinstance(i, list):
            for j in i:
                sum +=j
        else:
            sum += i        
    return sum
于 2019-05-30T05:54:59.070 回答
0
L = [1, 2, 3, [4, 5, 6], 5, [7, 8, 9]]
total = 0 # assign any var 
for a in L: # assign index and start to iterate using if else
    if (isinstance(a, list)): # since its a list you are basically repeating the prev step
        for b in a:
            total += b
    else:
        total += a
print(total)
于 2020-05-29T16:15:59.200 回答
0
def list_sum(L):
    return sum(list_sum(x) if isinstance(x, list) else x for x in L)
于 2021-06-15T11:57:15.093 回答
-1
def nested_sum(lists):
total = 0
for lst in lists:
    s = sum(lst)
    total += s
return total
于 2020-02-28T16:15:49.463 回答
-2
    #nested sum

    l = [[1, 2], [3,5], [6,2], [4, 5, 6,9]] 

    def nested_sum(lst):

       sum = 0

       for i in lst:
          for j in i:
             sum = sum + j
       
       print(sum)
    
   
nested_sum(l) 
于 2021-02-17T20:43:26.830 回答