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:
for nome in zip(nomes[0], nomes[1]):
nomes_comp.append(nome[0] ' ' nome[1])
CodePudding user response:
You can try:
nomes_comp = ["Fulano A", "Beltrano B", "Fulano A"]
out, cnt = [], {}
for n in nomes_comp:
if n in cnt:
cnt[n] = 1
out.append(f"{n}{cnt[n]}")
else:
cnt[n] = 0
out.append(n)
print(out)
Prints:
['Fulano A', 'Beltrano B', 'Fulano A1']
CodePudding user response:
Use a dictionary (or a collections.defaultdict
) to keep track of how many occurrences you've found.
nomes_comp = ['Fulano A', 'Beltrano B', 'Fulano A']
count_d = dict()
for i, n in enumerate(nomes_comp):
c = count_d.get(n, 0)
count_d[n] = c 1
if c:
nomes_comp[i] = n str(c)
After you do this, the original nomes_comp
is modified to:
['Fulano A', 'Beltrano B', 'Fulano A1']
CodePudding user response:
Use Counter.
from collections import Counter
counts = Counter(nomes_comp)
for name, count in counts:
if count > 1:
...
Generate and store a new unique name for such entries.
CodePudding user response:
You could use an OrderedDict from the collections module and add a character to the duplicate strings whenever a value is already present in the OrderedDict:
from collections import OrderedDict
nomes_comp = ['Fulano A', 'Beltrano B', 'Fulano A']
d = OrderedDict()
for nome in nomes_comp:
if nome in d:
d[nome '1'] = None
else:
d[nome] = None
nomes_comp = list(d.keys())
print(nomes_comp)
# ['Fulano A', 'Beltrano B', 'Fulano A1']
Salve do Brasil!