Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to count consecutive duplicates in a python list [duplicate]

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)
like image 447
Cameron Hiruta Avatar asked Sep 06 '16 03:09

Cameron Hiruta


2 Answers

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]
like image 88
Karin Avatar answered Oct 12 '22 21:10

Karin


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
like image 20
BallpointBen Avatar answered Oct 12 '22 21:10

BallpointBen