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