sum of nested list in Python

后端 未结 12 658
粉色の甜心
粉色の甜心 2020-12-10 05:30

I try to sum a list of nested elements

e.g, numbers=[1,3,5,6,[7,8]] should produce sum=30

I wrote the following code :



        
相关标签:
12条回答
  • 2020-12-10 05:53

    A quick recursion that uses a lambda to handle the nested lists:

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

    rec, applied on a list, will return the sum (recursively), on a value, return the value.

    result = rec(a)
    
    0 讨论(0)
  • 2020-12-10 05:54

    This code also works.

    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
    
    0 讨论(0)
  • 2020-12-10 05:54
     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)
    
    0 讨论(0)
  • 2020-12-10 05:55
    def nested_sum(lists):
    total = 0
    for lst in lists:
        s = sum(lst)
        total += s
    return total
    
    0 讨论(0)
  • 2020-12-10 05:59
    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
    
    0 讨论(0)
  • 2020-12-10 06:07

    It is generally considered more pythonic to duck type, rather than explicit type checking. Something like this will take any iterable, not just lists:

    def nested_sum(a) :
        total = 0
        for item in a :
            try:
                total += item
            except TypeError:
                total += nested_sum(item)
        return total
    
    0 讨论(0)
提交回复
热议问题