sum of nested list in Python

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

    An example using filter and map and recursion:

    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))
    

    And here is an example using reduce and 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)
    

    An example using plain old recursion:

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

    An example using simulated recursion:

    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
    

    Adjustment for handling self-referential lists is left as an exercise for the reader.

提交回复
热议问题