I’m trying to add a character to a specific duplicate string, like in the following situation:
nomes_comp = ['Fulano A', 'Beltrano B', 'Fulano A']
So I have duplicate items on my list; I would like to add another character in one of the duplicate items, hoping to get the following output:
nomes_comp = ['Fulano A', 'Beltrano B', 'Fulano A1']
I’m trying this way, but it’s not working:
JavaScript
x
3
1
for nome in zip(nomes[0], nomes[1]):
2
nomes_comp.append(nome[0] + ' ' + nome[1])
3
Advertisement
Answer
Use a dictionary (or a collections.defaultdict
) to keep track of how many occurrences you’ve found.
JavaScript
1
10
10
1
nomes_comp = ['Fulano A', 'Beltrano B', 'Fulano A']
2
3
count_d = dict()
4
5
for i, n in enumerate(nomes_comp):
6
c = count_d.get(n, 0)
7
count_d[n] = c + 1
8
if c:
9
nomes_comp[i] = n + str(c)
10
After you do this, the original nomes_comp
is modified to:
JavaScript
1
2
1
['Fulano A', 'Beltrano B', 'Fulano A1']
2