0

I have a list of names, like this

names =['Jack','Jerry',Jerry','Jerry','Jerry','Jerry','Phillips','Phillips','Phillips','Phillips','Harry','Harry','Harry','Harry','Harry'.....]

I want to rename duplicates as the resulting list should be like

names = ['Jack','Jerry',Jerry_2','Jerry_3','Jerry_4','Jerry_5','Phillips','Phillips_2','Phillips_3','Phillips_4','Harry','Harry_2','Harry_3','Harry_4','Harry_5'.....]

i have tried codes but my logic isn't well, is there anyone who can help me?

mhhabib
  • 2,975
  • 1
  • 15
  • 29
Hard work
  • 45
  • 3

3 Answers3

3

Just keep a dictionary of counts:

In [12]: names = ['Jack','Jerry', 'Jerry','Jerry','Jerry','Jerry','Phillips','Phillips','Phillips','Phillips','Harry','Harry','Harry','Harry','Harry']
    ...:
    ...:

In [13]: counts = {}

In [14]: for i, name in enumerate(names):
    ...:     if name in counts:
    ...:         counts[name] += 1
    ...:         names[i] = f"{name}_{counts[name]}"
    ...:     else:
    ...:         counts[name] = 1
    ...:

In [15]: names
Out[15]:
['Jack',
 'Jerry',
 'Jerry_2',
 'Jerry_3',
 'Jerry_4',
 'Jerry_5',
 'Phillips',
 'Phillips_2',
 'Phillips_3',
 'Phillips_4',
 'Harry',
 'Harry_2',
 'Harry_3',
 'Harry_4',
 'Harry_5']
juanpa.arrivillaga
  • 88,713
  • 10
  • 131
  • 172
1

Keep a dictionary of all the distinct names you've encountered and keep a count of how many times you've encountered them:

def rename_duplicates(names):
  seen = dict()
  
  for i, name in enumerate(names):
    if name not in seen:
      seencount[name] = 1
    else:
      seen[name] += 1
      names[i] += f'_{seen[name]}'
  
  return names
feverdreme
  • 467
  • 4
  • 12
0

Let's keep a Counter object to help us:

from collections import Counter

def update_repeats(lst) -> list:
    name_counter = Counter()
    for i in range(len(lst)):
        name_counter.update([lst[i]]) # update our counter
        if name_counter[lst[i]] > 1: # repeat, lets update our list value
            lst[i] = lst[i] + f'_{name_counter[lst[i]]}'
    return lst
M Z
  • 4,571
  • 2
  • 13
  • 27