Python - 将类似项目分组到字典值列表
给定一个元素列表,对相似元素进行分组,作为字典中的不同键值列表。
Input : test_list = [4, 6, 6, 4, 2, 2, 4, 8, 5, 8] Output : {4: [4, 4, 4], 6: [6, 6], 2: [2, 2], 8: [8, 8], 5: [5]} Explanation : Similar items grouped together on occurrences. Input : test_list = [7, 7, 7, 7] Output : {7 : [7, 7, 7, 7]} Explanation : Similar items grouped together on occurrences.
方法 #1:使用 defaultdict() + 循环
这是可以执行此任务的方式之一。在此,我们构造了一个带有默认列表的 defaultdict(),并不断将相似的值附加到相似的列表中。
Python3
# Python3 code to demonstrate working of
# Group Similar items to Dictionary Values List
# Using defaultdict + loop
from collections import defaultdict
# initializing list
test_list = [4, 6, 6, 4, 2, 2, 4, 4, 8, 5, 8]
# printing original list
print("The original list : " + str(test_list))
# using defaultdict for default list
res = defaultdict(list)
for ele in test_list:
# appending Similar values
res[ele].append(ele)
# printing result
print("Similar grouped dictionary : " + str(dict(res)))
Python3
# Python3 code to demonstrate working of
# Group Similar items to Dictionary Values List
# Using dictionary comprehension + Counter()
from collections import Counter
# initializing list
test_list = [4, 6, 6, 4, 2, 2, 4, 4, 8, 5, 8]
# printing original list
print("The original list : " + str(test_list))
# using * operator to perform multiplication
res = {key : [key] * val for key, val in Counter(test_list).items()}
# printing result
print("Similar grouped dictionary : " + str(res))
输出
The original list : [4, 6, 6, 4, 2, 2, 4, 4, 8, 5, 8]
Similar grouped dictionary : {4: [4, 4, 4, 4], 6: [6, 6], 2: [2, 2], 8: [8, 8], 5: [5]}
方法 #2:使用字典理解 + Counter()
这是可以执行此任务的另一种方式。在此,我们使用 Counter() 提取频率,然后使用乘法重复出现。
Python3
# Python3 code to demonstrate working of
# Group Similar items to Dictionary Values List
# Using dictionary comprehension + Counter()
from collections import Counter
# initializing list
test_list = [4, 6, 6, 4, 2, 2, 4, 4, 8, 5, 8]
# printing original list
print("The original list : " + str(test_list))
# using * operator to perform multiplication
res = {key : [key] * val for key, val in Counter(test_list).items()}
# printing result
print("Similar grouped dictionary : " + str(res))
输出
The original list : [4, 6, 6, 4, 2, 2, 4, 4, 8, 5, 8]
Similar grouped dictionary : {4: [4, 4, 4, 4], 6: [6, 6], 2: [2, 2], 8: [8, 8], 5: [5]}