繁体   English   中英

如何根据出现的行总结列表中的负数和正数

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

这是我的原始清单:

list1 = [1,2,5,-2,-3,5,6,-3,0,-2,1,0,2]

我需要创建一个总结正面和负面的列表,如下所示:

list2 = [8,-5,11,-5,3]

您可以过滤掉零个元素,然后使用itertools.groupby()将相同签名的项目组合在一起,然后将它们相加。

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

示例用法:

>>> values = [1, 2, 5, -2, -3, 5, 6, -3, 0, -2, 1, 0, 2]
>>> print(group_by_sign(values))
[8, -5, 11, -5, 3]

继续求和,在符号更改时追加/重置。

list2 = []
s = 0
for x in list1:
    if s * x < 0:
        list2.append(s)
        s = 0
    s += x
if s:
    list2.append(s)

这是带有注释行的解决方案。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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