Home > Blockchain >  Any way to print the sum of consecutive similar items in a list?
Any way to print the sum of consecutive similar items in a list?

Time:11-28

I'm looking for a way to print the sum of consecutive similar items in a list.

Is there a better code to do this? My code missing to give the last result! Any advice?

[Code]

lst=[' 1', '-1', '-1', '-1', ' 1', '-1', ' 1', ' 1']
output=[]
s=int(lst[0])
for i in range(1,len(lst)):
    if lst[i]==lst[i-1]:
        s =int(lst[i])
    else:
        output.append("{0: }".format(s))
        s=int(lst[i])

print(output)

[Input]

[' 1', '-1', '-1', '-1', ' 1', '-1', ' 1', ' 1']

[Expected Output]

[' 1', '-3', ' 1', '-1', ' 2']

[Current incomplete Output]

[' 1', '-3', ' 1', '-1']

CodePudding user response:

You can use itertools.groupby

>>> from itertools import groupby
>>>
>>> a = [' 1', '-1', '-1', '-1', ' 1', '-1', ' 1', ' 1']
>>>
>>> result = [sum(map(int, group)) for key, group in groupby(a)]
>>> result
[1, -3, 1, -1, 2]

But note that this will return a list of integers, but you can iterate over the result again to format it

>>> [f"{' ' if r > 0 else ''}{r}" for r in result]
[' 1', '-3', ' 1', '-1', ' 2']

CodePudding user response:

You need to keep track of your current_element also while summing up. And also the sum needs to be appended to the end after the for loop.

lst = [' 1', '-1', '-1', '-1', ' 1', '-1', ' 1', ' 1']
lst = [int(i) for i in lst]

output = []
s = lst[0]
current_element = lst[0]
for i in range(1,len(lst)):
    if current_element == lst[i]:
        s  = lst[i]
    else:
        output.append("{0: }".format(s))
        s = lst[i]
        current_element = lst[i]
output.append("{0: }".format(s))
        
print(output)

CodePudding user response:

Maybe use grupby from itertools:

from itertools import groupby

lst=[' 1', '-1', '-1', '-1', ' 1', '-1', ' 1', ' 1']
result = [f"{sum(map(int, l[1])): }" for l in groupby(lst)]
  • Related