📜  Python - 将相似的值列表分组到字典

📅  最后修改于: 2022-05-13 01:54:47.022000             🧑  作者: Mango

Python - 将相似的值列表分组到字典

有时,在使用Python列表时,我们可能会遇到一个问题,即我们需要将相似的值列表索引分组到字典中。这可以在我们需要分组字典作为列表对的输出的领域中有很好的应用。让我们讨论可以执行此任务的某些方式。

方法#1:使用字典理解
这是可以执行此任务的方式。在此,我们与另一个列表一起迭代一个列表,并使用一个列表中的相似键和另一个列表中的对应值继续构建字典。这是一种衬垫解决方案。

# Python3 code to demonstrate 
# Group similar value list to dictionary
# using dictionary comprehension
  
# Initializing lists
test_list1 = [4, 4, 4, 5, 5, 6, 6, 6, 6]
test_list2 = ['G', 'f', 'g', 'i', 's', 'b', 'e', 's', 't']
  
# printing original lists
print("The original list 1 is : " + str(test_list1))
print("The original list 2 is : " + str(test_list2))
  
# Group similar value list to dictionary
# using dictionary comprehension
res = {key : [test_list2[idx] 
      for idx in range(len(test_list2)) if test_list1[idx]== key]
      for key in set(test_list1)}
  
# printing result 
print ("Mapped resultant dictionary : " + str(res))
输出 :

方法 #2:使用defaultdict() + 循环
这是可以执行此任务的另一种方式。在这种情况下,我们通过创建 defaultdict() 来避免测试字典中的键是否存在。

# Python3 code to demonstrate 
# Group similar value list to dictionary
# using defaultdict() + loop
from collections import defaultdict
  
# Initializing lists
test_list1 = [4, 4, 4, 5, 5, 6, 6, 6, 6]
test_list2 = ['G', 'f', 'g', 'i', 's', 'b', 'e', 's', 't']
  
# printing original lists
print("The original list 1 is : " + str(test_list1))
print("The original list 2 is : " + str(test_list2))
  
# Group similar value list to dictionary
# using defaultdict() + loop
res = defaultdict(set)
for key, val in zip(test_list1, test_list2):
    res[key].add(val)
res = {key: list(val) for key, val in res.items()}
  
# printing result 
print ("Mapped resultant dictionary : " + str(res))
输出 :