This is my original list:
list1 = [1,2,5,-2,-3,5,6,-3,0,-2,1,0,2]
I need to create a list of sum-up positive and negative as below:
list2 = [8,-5,11,-5,3]
This is my original list:
list1 = [1,2,5,-2,-3,5,6,-3,0,-2,1,0,2]
I need to create a list of sum-up positive and negative as below:
list2 = [8,-5,11,-5,3]
Here is the solution with comment lines.
list1 = [1,2,5,-2,-3,5,6,-3,0,-2,1,0,2]
list2 = []
temp = 0
lastPositive = False
for i in list1: #Iterate through the list
if (i == 0): #If i is zero, continue
continue
if ((i > 0) == (1 if lastPositive else 0)): #if last element is positive and now is positive, add i to temp
temp += i
else: #if not, the positivity changes and add temp to list2
lastPositive = not lastPositive #Change the last positivity
list2.append(temp) if temp != 0 else print()
temp = i #Set temp to i for the rest of the list
list2.append(temp)
print(list2) #Then print the list
You can filter out zero elements, then use itertools.groupby() to group the same-signed items together, and then sum those.
from itertools import groupby
def group_by_sign(values):
nonzero = filter(None, values) # filters out falsey values
is_positive = lambda x: x > 0
return [sum(group) for key, group in groupby(nonzero, is_positive)]
Example usage:
>>> values = [1, 2, 5, -2, -3, 5, 6, -3, 0, -2, 1, 0, 2]
>>> print(group_by_sign(values))
[8, -5, 11, -5, 3]
Keep summing, append/reset at sign changes.
list2 = []
s = 0
for x in list1:
if s * x < 0:
list2.append(s)
s = 0
s += x
if s:
list2.append(s)