Search code examples
pythonlistlist-comprehension

Sum of elements in nested list using a list comprehensions


I am trying to calculate the sum of elements that are positive in each nested list.

    data = [[10, 6, -1, 2, -4, 3, -10, -3, -2, 4],
    [0, -3, -9, -1, 2, 6, -5, 8, -7, 0],
    [-2, -10, -2, -7, 8, 0, 1, 0, 8, -5]]

    sum_l = 0
    sum_list : list = list()
    sum_list = [[(sum_l+=y) for y in x] for x in data if y > 0]

I write it like this, but it gives an error: invalid syntax in (sum_l+=y). How do I fix it, and how to use list comprehensions correctly in general?

Thanks!


Solution

  • Use sum to sum the inner lists:

    data = [[10, 6, -1, 2, -4, 3, -10, -3, -2, 4],
            [0, -3, -9, -1, 2, 6, -5, 8, -7, 0],
            [-2, -10, -2, -7, 8, 0, 1, 0, 8, -5]]
    
    result = [sum(e for e in lst if e > 0) for lst in data]
    print(result)
    

    Output

    [25, 16, 17]
    

    Resources: