Find and replace duplicates in Array, but replace each nth instance with a different string

后端 未结 6 1696
栀梦
栀梦 2021-01-22 09:00

I have an array below which consists of repeated strings. I want to find and replace those strings, but each time a match is made I want to change the value of the replace strin

6条回答
  •  野性不改
    2021-01-22 09:31

    EDIT

    Counter and than sorting is simpler:

    L = ['champ', 'king', 'king', 'mak', 'mak', 'mak']
    counts = Counter(L)
    res = []
    for word in sorted(counts.keys()):
        if counts[word] == 1:
            res.append(word)
        else:
            res.extend(['{}{}'.format(word, index) for index in 
                       range(1, counts[word] + 1)])
    

    So this

    ['champ', 'mak', 'king', 'king', 'mak', 'mak']
    

    also gives:

    ['champ', 'king1', 'king2', 'mak1', 'mak2', 'mak3']
    

提交回复
热议问题