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

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

    One way would be to convert your array into a dictionary like that:

    SampleDict = {}
    for key in SampleArray:
        if key in SampleDict:
            SampleDict[key][0] = True # means: duplicates
            SampleDict[key][1] += 1 
        else:
            SampleDict[key] = [False, 1] # means: no duplicates
    

    Now you can easily convert that dict back to an array. However if the order in SampleArray is important, then you can do it like that:

    for i in range(len(SampleArray)):
        key = SampleArray[i]
        counter = SampleDict[key]
        if index[0]:
            SampleArray[i] = key + str(counter[1])
        counter[1] -= 1
    

    This will give you the reversed order however, i.e.

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

    But I'm sure you'll be able to tweak it to your needs.

提交回复
热议问题