📜  Python – 矩阵间分组

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

Python – 矩阵间分组

给定 2 个矩阵,每行有 2 个元素,根据第一个元素对它们进行分组。

方法 #1:使用 defaultdict() + 循环

这是可以执行此任务的方式之一。在此,我们迭代添加两个列表,然后从相似元素形成组并转换为具有值列表的字典。

Python3
# Python3 code to demonstrate working of 
# Inter Matrix Grouping
# Using defaultdict() + loop
from collections import defaultdict
  
# initializing lists
test_list1 = [[5, 8], [2, 0], [8, 4], [9, 3]]
test_list2 = [[8, 1], [9, 7], [2, 10], [5, 6]]
  
# printing original list
print("The original list 1 : " + str(test_list1))
print("The original list 2 : " + str(test_list2))
  
# initializing mapping list 
res = defaultdict(list)
  
# concatenation matrix using 2 lists
for key, val in test_list1 + test_list2:
    res[key].append(val)
  
# printing result 
print("The Grouped Matrix : " + str(dict(res)))


Python3
# Python3 code to demonstrate working of 
# Inter Matrix Grouping
# Using dictionary comprehension + dict()
  
# initializing lists
test_list1 = [[5, 8], [2, 0], [8, 4], [9, 3]]
test_list2 = [[8, 1], [9, 7], [2, 10], [5, 6]]
  
# printing original list
print("The original list 1 : " + str(test_list1))
print("The original list 2 : " + str(test_list2))
  
# mapping dictionaries together, converting each row to dictionary
res = {key: [dict(test_list1)[key], dict(test_list2)[key]] for key in dict(test_list1)}
  
# printing result 
print("The Grouped Matrix : " + str(dict(res)))


输出
The original list 1 : [[5, 8], [2, 0], [8, 4], [9, 3]]
The original list 2 : [[8, 1], [9, 7], [2, 10], [5, 6]]
The Grouped Matrix : {5: [8, 6], 2: [0, 10], 8: [4, 1], 9: [3, 7]}

方法 #2:使用字典理解 + dict()

这是可以执行此任务的另一种方式。在此,我们通过将每个矩阵转换为字典并将其值分组来迭代两个矩阵的所有元素。重要的是要在两个矩阵中跟踪每个元素的映射。

Python3

# Python3 code to demonstrate working of 
# Inter Matrix Grouping
# Using dictionary comprehension + dict()
  
# initializing lists
test_list1 = [[5, 8], [2, 0], [8, 4], [9, 3]]
test_list2 = [[8, 1], [9, 7], [2, 10], [5, 6]]
  
# printing original list
print("The original list 1 : " + str(test_list1))
print("The original list 2 : " + str(test_list2))
  
# mapping dictionaries together, converting each row to dictionary
res = {key: [dict(test_list1)[key], dict(test_list2)[key]] for key in dict(test_list1)}
  
# printing result 
print("The Grouped Matrix : " + str(dict(res)))
输出
The original list 1 : [[5, 8], [2, 0], [8, 4], [9, 3]]
The original list 2 : [[8, 1], [9, 7], [2, 10], [5, 6]]
The Grouped Matrix : {5: [8, 6], 2: [0, 10], 8: [4, 1], 9: [3, 7]}