sum of nested list in Python

后端 未结 12 702
粉色の甜心
粉色の甜心 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: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
    

提交回复
热议问题