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']
>Solution :
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']