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

Check for repetitions in a list and update it if so

We have a list, for instance one of the following:

lista = ['facility', 'resource', 'resource', 'resource', 'facility', 'other', 'resource', 'resource']
listb = ['facility', 'resource', 'other', 'another']

And we need a function that returns the following:

lista_new = ['facility', 'resource', 'resource1', 'resource2', 'facility1', 'other', 'resource3', 'resource4']
listb_new = ['facility', 'resource', 'other', 'another']

It would be great to do it without using Numpy, and it would be even better to obtain:

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

lista_new = ['facility0', 'resource0', 'resource1', 'resource2', 'facility1', 'other', 'resource3', 'resource4']
listb_new = ['facility', 'resource', 'other', 'another']

My possible solution is posted as a possible answer.

>Solution :

collections.Counter works just fine for this.

lista = ['facility', 'resource', 'resource', 'resource', 'facility',
         'other', 'resource', 'resource']
uniques = {label for label, count
           in collections.Counter(lista).items() if count == 1}
counter = collections.Counter()
def get_add(label):
    counter[label] += 1
    return counter[label] - 1
new_lista = [label if label in uniques else f"{label}{get_add(label)}"
             for label in lista]
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