在 Python 中为列表中的唯一数字分配值
pythonserver side programmingprogramming更新于 2025/11/13 17:48:17
很多时候我们需要唯一地标识列表中的元素。为此,我们需要为列表中的每个元素分配唯一的 ID。这可以通过以下两种方法使用 Python 中可用的不同内置函数来实现。
使用 enumerate 和 set
enumerate 函数为每个元素分配唯一的 ID。但是如果列表已经包含重复元素,那么我们需要创建一个包含列表的键值对的字典,并使用 set 函数分配唯一值。
示例
# 给定列表
Alist = [5,3,3,12]
print("The given list : ",Alist)
# 将 id 分配给值
enum_dict = {v: k for k, v in enumerate(set(Alist))}
list_ids = [enum_dict[n] for n in Alist]
# 打印字典的 id
print("唯一 id 列表为:",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
# 给定列表
Alist = [5,3,3,12]
print("给定列表:",Alist)
# 为列表元素分配唯一值
dict_ids = list(map({}.setdefault, Alist, count()))
# 结果
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]
相关文章
有用资源
python 参考教程 - 该教程包含有关 python 的更多信息:https://www.cainiaomax.com/python/

