[英]How to make only consecutive negative numbers add each other from a list mixed with positive numbers
我有一個清單如下:
a = [-10, 1, 5, 8, -5, -7, -2, 3, 4, 9, -1, -2]
我只想讓負數相加以獲得所需的輸出
a = [-10, 1, 5, 8, -14, 3, 4, 9, -3]
嘗試這個
a = [-10, 1, 5, 8, -5, -7, -2, 3, 4, 9, -1, -2];
finalList = [];
negSum = 0;
negCountStart = 0;
for i in a:
if(i < 0):
negCountStart = 1;
negSum = negSum + i;
else:
if negCountStart == 1:
finalList.append(negSum);
negSum = 0;
negCountStart = 0;
finalList.append(i);
if negCountStart:
finalList.append(negSum);
print(finalList)
似乎是itertools.groupby
/ itertools.chain
的一個很好的用例:
a = [-10, 1, 5, 8, -5, -7, -2, 3, 4, 9, -1, -2]
from itertools import groupby, chain
out = list(chain.from_iterable([sum(g)] if k else g
for k,g in groupby(a, lambda x: x<0)))
輸出: [-10, 1, 5, 8, -14, 3, 4, 9, -3]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.