sum of nested list in Python

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

提交回复
热议问题