Reputation: 470
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:
my_list = [1,1,1,0,0,0,1,1,0,0,0,1,1,0,0,0,1]
final_list = [3,0,2,0,2,0,1]
Similarly, here is another example:
my_second_list = [1,1,0,0,0,1,0,0,1]
expected_outcome= [2,0,1,0,1]
Upvotes: 1
Views: 487
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