You can use the dict and list expressions:
>>> a = ["a","b","a","c","b","a"] >>> d = {x:i for i, x in enumerate(set(a))} >>> [d[item] for item in a] [0, 2, 0, 1, 2, 0]
To keep order:
>>> seen = set() >>> d = { x:i for i, x in enumerate(y for y in a if y not in seen and not seen.add(y))} >>> [d[item] for item in a] [0, 1, 0, 2, 1, 0]
The above understanding of dict is equivalent:
>>> seen = set() >>> lis = [] for item in a: if item not in seen: seen.add(item) lis.append(item) ... >>> lis ['a', 'b', 'c'] >>> d = {x:i for i,x in enumerate(lis)}
source share