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, increment with a digit added to the string end.
Here is my list:
a = ['abc', 'abc', 'h', 'xv', 'xv', 'xv', 'h', 'h', 'h', 'h']
Expected list output:
['abc', 'abc1', 'h', 'xv', 'xv1', 'xv2', 'h1', 'h2', 'h3', 'h4']
I tried with this below 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)
The output I get:
['abc', 'abc1', 'h', 'xv', 'xv1', 'xv1', 'h1', 'h1', 'h1', 'h1']
But it is not giving the correct results and is not an optimized one. It will be great if I can get a list comprehension for this problem or an optimized one-liner?
CodePudding user response:
You can use a dictionary to keep track of the number of occurrences of a string seen so far. You could use a list comprehension, but the only way I could think of would involve list slicing and .count() or something super hacky, both of which would be less desirable than the one-pass implementation below:
a = ['abc', 'abc', 'h', 'xv', 'xv', 'xv', 'h', 'h', 'h', 'h']
result = []
occurrences = {}
for index, elem in enumerate(a):
if elem in occurrences:
elem_to_add = elem str(occurrences[elem])
occurrences[elem] = 1
else:
elem_to_add = elem
occurrences[elem] = 1
result.append(elem_to_add)
print(result)
CodePudding user response:
Use a dictionary to keep track of the items while you traverse a.
d = {}
out = []
for i in a:
if i not in d:
out.append(i)
d[i] = 1
else:
out.append(i str(d[i]))
d[i] = 1
Output:
>> print(out)
['abc', 'abc1', 'h', 'xv', 'xv1', 'xv2', 'h1', 'h2', 'h3', 'h4']
CodePudding user response:
Please try with this
a = ['abc', 'abc', 'h', 'xv', 'xv', 'xv', 'h', 'h', 'h', 'h']
new = []
for i in a:
if i in new:
index = 1
while i str(index) in new:
index = 1
if index == 1:
new.append(i '1')
else:
new.append(i str(index))
else:
new.append(i)
print(new)
CodePudding user response:
if you dont want to create a dictionary to store and also don't want to create a new list but make edit in the original, you can use this:
count = 0
i = 0
for word in a:
i = 1
for subindex in range(i,len(a)):
if word == a[subindex]:
count = 1
a[subindex] = word str(count)
count = 0
