0

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?

Poonam
  • 31
  • 1
  • 4
  • 1
    What should happen if there is only one 1 in your input list? – mkrieger1 Apr 29 '23 at 17:01
  • @mkrieger1 Nothing, because in my code I set the value of n with least occurred item in the list, so for the example the n will have the value of 3 because the least occurred item is 1 and it occurred 3 times – Poonam Apr 29 '23 at 17:08
  • 3
    What should happen if the items in the list that are the same are not contiguous? – mkrieger1 Apr 29 '23 at 17:42
  • Same behavior as if they are contiguous – Poonam Apr 29 '23 at 18:28

2 Answers2

3
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]
Kelly Bundy
  • 23,480
  • 7
  • 29
  • 65
2

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]
RomanPerekhrest
  • 88,541
  • 4
  • 65
  • 105