Python - 矩阵中的组元素
给定一个包含两列的矩阵,根据第一列对第二列元素进行分组。
Input : test_list = [[5, 8], [2, 0], [5, 4], [2, 3], [2, 9]]
Output : {5: [8, 4], 2: [0, 3, 9]}
Explanation : 8 and 4 are mapped to 5 in Matrix, all others to 2.
Input : test_list = [[2, 8], [2, 0], [2, 4], [2, 3], [2, 9]]
Output : {2: [8, 4, 0, 3, 9]}
Explanation : All mapped to 2.
方法#1:使用字典理解+循环
这是可以执行此任务的方式之一。在此,我们使用第 1 行的空列表值构造字典,然后运行循环将值分配给它。
Python3
# Python3 code to demonstrate working of
# Group Elements in Matrix
# Using dictionary comprehension + loop
# initializing list
test_list = [[5, 8], [2, 0], [5, 4], [2, 3], [7, 9]]
# printing original list
print("The original list : " + str(test_list))
# initializing empty dictionary with default empty list
res = {idx[0]: [] for idx in test_list}
# using loop for grouping
for idx in test_list:
res[idx[0]].append(idx[1])
# printing result
print("The Grouped Matrix : " + str(res))
Python3
# Python3 code to demonstrate working of
# Group Elements in Matrix
# Using loop + defaultdict()
from collections import defaultdict
# initializing list
test_list = [[5, 8], [2, 0], [5, 4], [2, 3], [7, 9]]
# printing original list
print("The original list : " + str(test_list))
# initializing empty dictionary using defaultdict
res = defaultdict(list)
# using loop for grouping
for idx in test_list:
res[idx[0]].append(idx[1])
# printing result
print("The Grouped Matrix : " + str(dict(res)))
输出
The original list : [[5, 8], [2, 0], [5, 4], [2, 3], [7, 9]]
The Grouped Matrix : {5: [8, 4], 2: [0, 3], 7: [9]}
方法 #2:使用循环 + defaultdict()
这与上述方法类似。不同之处在于初始空网格是使用 defaultdict() 创建的。
Python3
# Python3 code to demonstrate working of
# Group Elements in Matrix
# Using loop + defaultdict()
from collections import defaultdict
# initializing list
test_list = [[5, 8], [2, 0], [5, 4], [2, 3], [7, 9]]
# printing original list
print("The original list : " + str(test_list))
# initializing empty dictionary using defaultdict
res = defaultdict(list)
# using loop for grouping
for idx in test_list:
res[idx[0]].append(idx[1])
# printing result
print("The Grouped Matrix : " + str(dict(res)))
输出
The original list : [[5, 8], [2, 0], [5, 4], [2, 3], [7, 9]]
The Grouped Matrix : {5: [8, 4], 2: [0, 3], 7: [9]}