pythonlistfind-occurrences

Remove N occurrences of each item in a list


I am trying to remove N occurrences of each item in a list using python, this is the code I am using :

numbers = [1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3]
n = 2

result = []

for i in set(numbers):
    if numbers.count(i) > n:
        print(numbers.count(i) - n)
        result += [i] * (numbers.count(i) - n)

print(result) # [1, 2, 2, 3, 3, 3, 3]

For n = 3, the result will be [2, 3, 3, 3]

Is there a better or one-liner way to do it?


Solution

  • With itertools.groupby + itertools.chain:

    from itertools import groupby, chain
    
    numbers = [1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3]
    n = 3
    res = list(chain.from_iterable([gr[n:] for _, gr in ((_, list(gr))
                                    for _, gr in groupby(numbers)) if len(gr) > n]))
    print(res)
    

    [2, 3, 3, 3]