将值分配给Python中列表中的唯一编号

很多时候,我们需要唯一地标识列表中的元素。为此,我们需要为列表中的每个元素分配唯一的ID。这可以通过以下两种方法使用Python中可用的不同内置函数来实现。

与枚举和设置

枚举函数为每个元素分配唯一的ID。但是,如果列表已经是重复的元素,那么我们需要创建一个由列表组成的键值对字典,并使用set函数分配唯一值。

示例

# Given List
Alist = [5,3,3,12]
print("The given list : ",Alist)

# Assigning ids to values
enum_dict = {v: k for k, v in enumerate(set(Alist))}
list_ids = [enum_dict[n] for n in Alist]

# Print ids of the dictionary
print("The list of unique ids is: ",list_ids)

输出结果

运行上面的代码给我们以下结果-

The given list : [5, 3, 3, 12]
The list of unique ids is: [2, 0, 0, 1]

count()map()

map()函数将相同的函数一次又一次地应用于传递给它的不同参数。但是count方法返回具有指定值的元素数。因此,在下面的程序中,我们将这两者结合起来以获得给定列表元素的唯一ID列表。

示例

from itertools import count

# Given List
Alist = [5,3,3,12]
print("The given list : ",Alist)

# Assign unique value to list elements
dict_ids = list(map({}.setdefault, Alist, count()))

# The result
print("The list of unique ids is: ",dict_ids)

输出结果

运行上面的代码给我们以下结果-

The given list : [5, 3, 3, 12]
The list of unique ids is: [0, 1, 1, 3]