Search code examples
pythonstringunique

How to add labels to strings with letters in python list?


I wrote some code that work fine but I would like to make it more precise.

The idea is to add a letter showing the occurence of the element in the list. The initial list look like this

['1','2','1','2','1']

And I want

['1a','2a','1b','2b','1c']

I'm sure there is a quick answer or function to do this, does anyone have an idea ?

My code below :

ancestrals = ['1','2','1','2','1']
uni_a = list(set(ancestrals))
for i in range(len(ancestrals)):
    tmp = uni_a.index(ancestrals[i])
    if uni_a[tmp][-1].isalpha():
        val = ancestrals[i][:1] + chr(ord(uni_a[tmp][-1])+1)
    else:
        val = ancestrals[i] + "a"

    ancestrals[i] = val

    while uni_a[tmp] in ancestrals[i:]:
        p = ancestrals[i:].index(uni_a[tmp])+ i
        ancestrals[p] = val

    uni_a[tmp] = ancestrals[i]
print(ancestrals)

Solution

  • ancestrals = ['1','2','1','2','1']
    
    count = {}
    for i, anc in enumerate(ancestrals):
        cnt = count.get(anc, 0)
        count[anc] = cnt + 1
        ancestrals[i] += chr(ord('a') + cnt)
    
    print (ancestrals)
    # --> ['1a', '2a', '1b', '2b', '1c']
    

    Of course, that will only work if the maximum count per element is 26 (letter “z”).