简体   繁体   中英

How to sum up negative and positive numbers in a list based on the row they occur

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]

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)

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM