Python – 附加相似的值作为键
有时,在处理数据时,我们可能会遇到需要将特定列表和值分类为相似键的问题。这可能是计算数据的问题。就像计算选票或计算硬币一样。让我们讨论可以执行此任务的某些方式。
方法#1:使用循环
这是可以执行此任务的粗暴方式。在此,我们运行一个循环将值添加到字典值列表中,如果不存在,我们动态创建键并执行附加。
# Python3 code to demonstrate working of
# Append Similar Values as Key
# Using loop
# initializing list
test_list = ['Manjeet', 'Nikhil', 'Akshat', 'Akash',
'Manjeet', 'Akash', 'Akshat', 'Manjeet']
# printing original list
print("The original list is : " + str(test_list))
# Append Similar Values as Key
# Using loop
res = dict()
for ele in test_list:
try:
res[ele].append(ele)
except KeyError:
res[ele] = [ele]
# printing result
print("The similar values dictionary is : " + str(res))
The original list is : [‘Manjeet’, ‘Nikhil’, ‘Akshat’, ‘Akash’, ‘Manjeet’, ‘Akash’, ‘Akshat’, ‘Manjeet’]
The similar values dictionary is : {‘Nikhil’: [‘Nikhil’], ‘Manjeet’: [‘Manjeet’, ‘Manjeet’, ‘Manjeet’], ‘Akash’: [‘Akash’, ‘Akash’], ‘Akshat’: [‘Akshat’, ‘Akshat’]}
方法 #2:使用defaultdict()
+ 循环
上述功能的组合可以用来解决这个问题。在此,我们使用 defaultdict() 预初始化字典。
# Python3 code to demonstrate working of
# Append Similar Values as Key
# Using defaultdict() + loop
from collections import defaultdict
# initializing list
test_list = ['Manjeet', 'Nikhil', 'Akshat', 'Akash',
'Manjeet', 'Akash', 'Akshat', 'Manjeet']
# printing original list
print("The original list is : " + str(test_list))
# Append Similar Values as Key
# Using defaultdict() + loop
res = defaultdict(list)
for sub in test_list:
res[sub].append(sub)
# printing result
print("The similar values dictionary is : " + str(dict(res)))
The original list is : [‘Manjeet’, ‘Nikhil’, ‘Akshat’, ‘Akash’, ‘Manjeet’, ‘Akash’, ‘Akshat’, ‘Manjeet’]
The similar values dictionary is : {‘Nikhil’: [‘Nikhil’], ‘Manjeet’: [‘Manjeet’, ‘Manjeet’, ‘Manjeet’], ‘Akash’: [‘Akash’, ‘Akash’], ‘Akshat’: [‘Akshat’, ‘Akshat’]}