[英]How to make only consecutive negative numbers add each other from a list mixed with positive numbers
I have a list as follows:我有一个清单如下:
a = [-10, 1, 5, 8, -5, -7, -2, 3, 4, 9, -1, -2]
I would like to make only the negative numbers add each other to have the desired output of我只想让负数相加以获得所需的输出
a = [-10, 1, 5, 8, -14, 3, 4, 9, -3]
Try this尝试这个
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)
Seems like a good use case for itertools.groupby
/ itertools.chain
:似乎是
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)))
output: [-10, 1, 5, 8, -14, 3, 4, 9, -3]
输出:
[-10, 1, 5, 8, -14, 3, 4, 9, -3]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.