I have the following list of duplicate items in list:
x = ['John', "Jill", "Ron", "John", "Jill", "John", "Tom", "Harry", "Harry"]
I want to get the following output:
out = ['John_1', "Jill_1", "Ron_1", "John_2", "Jill_2", "John_3", "Tom_1", "Harry_1", "Harry_2"]
I wrote the following code:
from collections import Counter
def iterate_string_duplicates(x):
nl = []
dct = dict(Counter(x))
for k,v in dct.items():
for i in list(range(1,v+1)):
nl.append(k+"_"+str(i))
return nl
But I get the following output because of using the dictionary approach:
iterate_string_duplicates(x)
output: ['John_1', 'John_2', 'John_3', 'Jill_1', 'Jill_2', 'Ron_1', 'Tom_1', 'Harry_1', 'Harry_2']
I'm looking for an approach where the order of the initial strings won't change.