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)
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]
def count_dups(L):
ans = []
if not L:
return ans
running_count = 1
for i in range(len(L)-1):
if L[i] == L[i+1]:
running_count += 1
else:
ans.append(running_count)
running_count = 1
ans.append(running_count)
return ans
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With