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

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

    groupby is a convenient way to group duplicates:

    >>> from itertools import groupby
    >>> FinalArray = []
    >>> for k, g in groupby(SampleArray):
        # g is an iterator, so get a list of it for further handling
        items = list(g)
        # If only one item, add it unchanged
        if len(items) == 1:
            FinalArray.append(k)
        # Else add index at the end
        else:
            FinalArray.extend([j + str(i) for i, j in enumerate(items, 1)])
    
    
    >>> FinalArray
    ['champ', 'king1', 'king2', 'mak1', 'mak2', 'mak3']
    

提交回复
热议问题