![](/img/trans.png)
[英]Function that returns a list of the count of positive numbers and sum of negative numbers
[英]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.