I have a list of strings with repeated elements present. I have to recreate the list with a condition that if the string is already present in the list, I need to append a number to the end of the string.
Here is my list:
a = ['abc', 'abc', 'h', 'xv', 'xv', 'xv', 'h', 'h', 'h', 'h']
I expect the following output:
['abc', 'abc1', 'h', 'xv', 'xv1', 'xv2', 'h1', 'h2', 'h3', 'h4']
I tried to accomplish this with the following code:
new = []
for i in a:
if i in new:
if i[:-1].isdigit():
new.append(i + str(int(i[-1]) + 1))
else:
new.append(i + '1')
else:
new.append(i)
But I'm getting:
['abc', 'abc1', 'h', 'xv', 'xv1', 'xv1', 'h1', 'h1', 'h1', 'h1']
But it is not giving the correct results. It will be great if I can get a list comprehension or an optimized one-liner for this problem.