Deepak
Deepak

Reputation: 470

Sum adjacent elements of a list if their values are equal using list comprehension in python

I am facing this problem where I need to add adjacent elements of a list if their value are equal in Python. Below are my list and expected outcome:

Similarly, here is another example:

Upvotes: 1

Views: 487

Answers (1)

Selcuk
Selcuk

Reputation: 59174

You can use itertools.groupby on an unsorted list:

>>> from itertools import groupby
>>> [sum(group) for _, group in groupby(my_list)]
[3, 0, 2, 0, 2, 0, 1]

Upvotes: 1

Related Questions