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
Here is a similar factorizing solution with collections.defaultdict
and itertools.count
:
import itertools as it
import collections as ct
names = ['ll', 'll', 'hl', 'hl', 'LL', 'LL', 'LL', 'HL', 'll']
dd = ct.defaultdict(it.count().__next__)
[dd[i] for i in names]
# [0, 0, 1, 1, 2, 2, 2, 3, 0]
Every new occurrence calls the next integer in itertools.count
and adds new entry to dd
.
You can Try This Also:-
names = ['ll', 'll', 'll', 'hl', 'hl', 'hl', 'LL', 'LL', 'LL', 'HL', 'HL', 'HL']
indexList = list(set(names))
print map(lambda name:indexList.index(name),names)