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

后端 未结 6 1694
栀梦
栀梦 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:43

    Assuming you want the array sorted :

    import collections    
    counter = collections.Counter(SampleArray)
    res = []
    for key in sorted(counter.keys()):
        if counter[key] == 1:
            res.append(key)
        else:
            res.extend([key+str(i) for i in range(1, counter[key]+1)])
    
    >>> res
    ['champ', 'king1', 'king2', 'mak1', 'mak2', 'mak3']
    

提交回复
热议问题