Use a defaultdict and use a counter as a default value function.
Whenever the key exists, it returns the stored "first encountered position", otherwise it calls Incr.__call__
which increments its count to provide a new first encountered position.
With super brain's suggestion, use an existing counter class:
from collections import defaultdict
from itertools import count
li = ['pea', 'rpai', 'rpai', 'schiai', 'pea', 'rpe', 'zoi', 'zoi', 'briai', 'rpe']
seen = defaultdict(count().__next__)
print( [seen[val] for val in li] )
Rolling my own Incr, as before, which does give you the advantage that you could return anything (such as a GUID):
from collections import defaultdict
class Incr:
def __init__(self):
self.count = -1
def __call__(self):
self.count +=1
return self.count
li = ['pea', 'rpai', 'rpai', 'schiai', 'pea', 'rpe', 'zoi', 'zoi', 'briai', 'rpe']
seen = defaultdict(Incr())
print( [seen[val] for val in li] )
both provide same output:
[0, 1, 1, 2, 0, 3, 4, 4, 5, 3]