Python find duplicates which occur more than 3 times

I good use case for itertools.groupby:

>>> from itertools import groupby
>>> list_before = [1, 1, 1, 2, 3, 4, 5, 5, 5, 6, 6, 7, 7, 7, 8, 8, 8, 8, 8]
>>> list_after = []
>>> for k, group in groupby(list_before):
...     lst = list(group)
...     if len(lst) >= 3:
...         list_after.append(k)
...     else:
...         list_after.extend(lst)
>>> list_after
[1, 2, 3, 4, 5, 6, 6, 7, 8]

It would be possible make a one-liner with itertools.chain but the for loop is almost certainly more readable and similarly performant.


>>> from itertools import groupby
>>> nums = [1, 1, 1, 2, 3, 4, 5, 5, 5, 6, 6, 7, 7, 7, 8, 8, 8, 8, 8]
>>> [k for k, g in groupby(nums) for i in range(1 + (len(list(g)) == 2))] 
[1, 2, 3, 4, 5, 6, 6, 7, 8]

Tags:

Python

List