将列表转换为ID列表

Spu*_*Spu 1 python list python-3.x

Python 3.3:

从列表中获取最简单的方法是什么:

input = ["A", 112, "apple", 74, 112]
Run Code Online (Sandbox Code Playgroud)

以下列表:

output = [0, 1, 2, 3, 1]
Run Code Online (Sandbox Code Playgroud)

也就是说,分配从0开始自动递增的id到每个唯一条目,并将原始列表转换为此id的列表.

我知道,我可以获得便宜的课程数量

number_of_classes = len(set(input))
Run Code Online (Sandbox Code Playgroud)

但是如何创建正确有序的输出?

Ale*_*ley 13

您可以使用列表推导来创建元素首次出现在该列表中的索引列表.

对于输入列表i = ["A", 112, "apple", 74, 112]:

>>> [i.index(value) for value in i]
[0, 1, 2, 3, 1]
Run Code Online (Sandbox Code Playgroud)