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
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']