Cameron Hiruta Cameron Hiruta - 3 months ago 18
Python Question

how to count consecutive duplicates in a python list

I have a list as follows, consisting of only (-1)s and 1s:

list1=[-1,-1,1,1,1,-1,1]


I'm trying to append the number of consecutive duplicates into a list, e.g.:

count_dups=[2,3,1,1]


I've tried creating a new list and using the zip function as the first step, but
can't seem to go on because of the cut-off end-value

list2=list1[1:]
empty=[]
for x,y in zip(list1,list2):
if x==y:
empty.append(x)
else:
empty.append(0)

Answer

You can use itertools.groupby:

from itertools import groupby
list1 = [-1, -1, 1, 1, 1, -1, 1]
count_dups = [sum(1 for _ in group) for _, group in groupby(list1)]
print(count_dups)

Output:

[2, 3, 1, 1]