I’m looking for a function to limit the number of duplicates in a list. For example in the list below, we have three ‘1’s, one ‘2’, two ‘a’s, and three ‘b’s.
initial_list = [1,2,1,1,'a','b','a', 'b','b']
def cap(initial_list, n=2)
If I was to limit the number of duplicates to n=2, I would get:
[1,2,1,'a','b','a', 'b']
The order of the items in the output does not matter.
>Solution :
You need to keep track of the number of values enountered. You can use dictionary for this (defaultdict even better):
from collections import defaultdict
def cap(initial_list, n=2):
counter = defaultdict(int)
result = []
for e in initial_list:
if counter[e] < n:
result.append(e)
counter[e] += 1
return result
initial_list = [1,2,1,1,'a','b','a', 'b','b']
cap(initial_list)
output:
[1, 2, 1, 'a', 'b', 'a', 'b']