Home > Net >  How to make only consecutive negative numbers add each other from a list mixed with positive numbers
How to make only consecutive negative numbers add each other from a list mixed with positive numbers

Time:06-16

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]

CodePudding user response:

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)

CodePudding user response:

Seems like a good use case for 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]

  • Related