sum of nested list in Python

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

提交回复
热议问题