Home > OS >  How to Print the sum of all the consecutive negative values
How to Print the sum of all the consecutive negative values

Time:03-29

I wish to print the sum of all the consecutive negative values of a list

Example

lst = [1,-1,-3,2,3,4,-5,-1,-3,5,-3,-1,5,4]

I want to print the sum of :

(-1, -3) ;(-5,-1,-3); (-3,-1)

CodePudding user response:

Use itertools.groupby in a list comprehension:

lst = [1,-1,-3,2,3,4,-5,-1,-3,5,-3,-1,5,4]

from itertools import groupby
out = [sum(g) for k,g in groupby(lst, lambda x: x<0) if k]

output: [-4, -9, -4]

CodePudding user response:

def sum_consecutive(values):
    accumulator = 0
    for value in values:
        if value >= 0:
            if accumulator != 0:
                print(accumulator)
            accumulator = 0
        else:
            accumulator  = value

Should work

  • Related