Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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]

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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']
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading