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:

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]

Leave a Reply