I have a list of strings. I want to assign a unique number to each string (the exact number is not important), and create a list of the same length using these numbers, in o
To make it more generic you can wrap it in a function, so these hard-coded values don't do any harm, because they are local.
If you use efficient lookup-containers (I'll use a plain dictionary) you can keep the first index of each string without loosing to much performance:
def your_function(list_of_strings):
encountered_strings = {}
result = []
idx = 0
for astring in list_of_strings:
if astring in encountered_strings: # check if you already seen this string
result.append(encountered_strings[astring])
else:
encountered_strings[astring] = idx
result.append(idx)
idx += 1
return result
And this will assign the indices in order (even if that's not important):
>>> your_function(['ll', 'll', 'll', 'hl', 'hl', 'hl', 'LL', 'LL', 'LL', 'HL', 'HL', 'HL'])
[0, 0, 0, 1, 1, 1, 2, 2, 2, 3, 3, 3]
This needs only one iteration over your list of strings, which makes it possible to even process generators and similar.