为Python列表中的每个唯一值分配ID
在使用 Python 字典时,我们可能需要唯一地识别字典的每个元素。为此,我们必须为字典中的每个元素分配唯一的 ID。在本文中,我们将了解如何为 Python 字典中的重复元素分配相同的唯一 ID。
使用 enumerate() 和 OrderedDict.fromkeys()
enumerate 函数通过为字典的每个元素添加一个计数器来扩展给定的字典。然后,我们应用 OrderedDict.fromkeys(),它将从字典中提取相同的计数器值,从而消除 ID 的重复值。
示例
from collections import OrderedDict
Alist = ['Mon','Tue','Wed','Mon',5,3,3]
print("The given list : ",Alist)
# Assigning ids to values
list_ids = [{v: k for k, v in enumerate(
OrderedDict.fromkeys(Alist))}
[n] for n in Alist]
# The result
print("The list of ids : ",list_ids)输出
运行上述代码将得到以下结果:
The given list : ['Mon', 'Tue', 'Wed', 'Mon', 5, 3, 3] The list of ids : [0, 1, 2, 0, 3, 4, 4]
使用来自 collections 的 OrderedDict
在这种方法中,我们使用 defaultdict 函数,它只为新元素分配新的键。然后,我们使用 lambda 函数循环遍历唯一 ID 的新列表。
示例
from collections import defaultdict
# Given List
Alist = ['Mon','Tue','Wed','Mon',5,3,3]
print("The given list : ",Alist)
# Assigning ids to values
d_dict = defaultdict(lambda: len(d_dict))
list_ids= [d_dict[n] for n in Alist]
# Print ids of the dictionary
print("The list of ids : ", list_ids)输出
运行上述代码将得到以下结果:
The given list : ['Mon', 'Tue', 'Wed', 'Mon', 5, 3, 3] The list of ids : [0, 1, 2, 0, 3, 4, 4]
广告
数据结构
网络
关系数据库管理系统 (RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP