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

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

    f = ['champ', 'king', 'king', 'mak', 'mak', 'mak']
    
    fields_out = [x + str(f.count(x) - f[i + 1:].count(x)) for i, x in enumerate(f)]
    print(fields_out)
    
    >>['champ1', 'king1', 'king2', 'mak1', 'mak2', 'mak3']
    

    or

    fields_out = [(x if i == f.index(x) else x + str(f.count(x) - f[i + 1:].count(x))) for i, x in enumerate(f)]
    print(fields_out)
    
    >>['champ', 'king', 'king2', 'mak', 'mak2', 'mak3']
    

提交回复
热议问题