How to assign ordinal numbers of unique values to a list in Python?

Viewed 851

Suppose I have a list

A = ['A', 'A', 'A', 'B', 'B', 'C']

How to turn it to

B = [0, 0, 0, 1, 1, 2]

?

I wrote this way

C = {t[1]:t[0] for t in enumerate(list(set(A)))}
B = [C[e] for e in A]

and it gave

[1, 1, 1, 2, 2, 0]

i.e. the order appeared random and also the entire code looks complex.

Is there any simpler way?

5 Answers
Related