Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Python cap number of occurences of duplicate items in a list

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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']
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading