sum of nested list in Python

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

    A simple solution would be to use nested loops.

    def nested_sum(t):
    
        sum=0
        for i in t:
            if isinstance(i, list):
                for j in i:
                    sum +=j
            else:
                sum += i        
        return sum
    
    0 讨论(0)
  • 2020-12-10 05:42

    You need to use isinstance to check whether an element is a list or not. Also, you might want to iterate over the actual list, to make things simpler.

    def nested_sum(L):
        total = 0  # don't use `sum` as a variable name
        for i in L:
            if isinstance(i, list):  # checks if `i` is a list
                total += nested_sum(i)
            else:
                total += i
        return total
    
    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2020-12-10 05:48

    I would sum the flattened list:

    def flatten(L):
        '''Flattens nested lists or tuples with non-string items'''
        for item in L:
            try:
                for i in flatten(item):
                    yield i
            except TypeError:
                yield item
    
    
    >>> sum(flatten([1,3,5,6,[7,8]]))
    30
    
    0 讨论(0)
  • 2020-12-10 05:48
    L = [1, 2, 3, [4, 5, 6], 5, [7, 8, 9]]
    total = 0 # assign any var 
    for a in L: # assign index and start to iterate using if else
        if (isinstance(a, list)): # since its a list you are basically repeating the prev step
            for b in a:
                total += b
        else:
            total += a
    print(total)
    
    0 讨论(0)
  • 2020-12-10 05:49

    One alternative solution with list comprehension:

    >>> sum( sum(x) if isinstance(x, list) else x for x in L )
    30
    

    Edit: And for lists with more than two levels(thx @Volatility):

    def nested_sum(L):
        return sum( nested_sum(x) if isinstance(x, list) else x for x in L )
    
    0 讨论(0)
提交回复
热议问题