Remove N occurrences of each item in a list

69 Views Asked by At

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?

2

There are 2 best solutions below

3
RomanPerekhrest On BEST ANSWER

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]
0
Kelly Bundy On
from collections import Counter

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

ctr = Counter(numbers)
ctr -= dict.fromkeys(ctr, n)
result = list(ctr.elements())

print(result)

Output (Attempt This Online!):

[1, 2, 2, 3, 3, 3, 3]