If you don't care about the original order, you can think of it this way:
- Count the number of views of each name
- Create a list in which if the name appears only once, we do not add anything, but if it appears more than once, it adds
_1 , _2 ... to the second and subsequent appearances.
This means that you can use collections.Counter to complete the task:
import collections names = ['Alice', 'Bob', 'Carl', 'Dave', 'Bob', 'Earl', 'Carl', 'Frank', 'Carl'] counter = collections.Counter(names) print("Counter: %s" % counter) result = [] for name, counts in counter.iteritems(): result.append(name) for i in range(1, counts): result.append("%s_%d" % (name, i)) print(result)
What outputs:
Counter: Counter({'Carl': 3, 'Bob': 2, 'Earl': 1, 'Frank': 1, 'Alice': 1, 'Dave': 1}) ['Earl', 'Frank', 'Alice', 'Dave', 'Carl', 'Carl_1', 'Carl_2', 'Bob', 'Bob_1']
If you want to add the suffix _1 , _2 to all names that contain more than one entry in the list, but leave the names that appear only once, you can do:
import collections names = ['Alice', 'Bob', 'Carl', 'Dave', 'Bob', 'Earl', 'Carl', 'Frank', 'Carl'] counter = collections.Counter(names) print("Counter: %s" % counter) result = [] for name, counts in counter.iteritems(): if counts == 1: result.append(name) else: for i in range(counts): result.append("%s_%d" % (name, i + 1)) print(result)
What outputs:
Counter: Counter({'Carl': 3, 'Bob': 2, 'Earl': 1, 'Frank': 1, 'Alice': 1, 'Dave': 1}) ['Earl', 'Frank', 'Alice', 'Dave', 'Carl_1', 'Carl_2', 'Carl_3', 'Bob_1', 'Bob_2']