Python – 将坐标字典转换为矩阵
有时,在使用Python Matrix 时,我们可能会遇到字典记录的问题,其中键为矩阵位置及其值,我们希望将其转换为实际的 Matrix。这可以在许多领域有应用,包括竞争性编程和日间编程。让我们讨论可以执行此任务的某些方式。
方法 #1:使用循环 + max()
+ 列表推导
上述方法的组合可以用来解决这个问题。在此,我们使用 max() 来获取矩阵的维度,使用列表推导来创建矩阵并使用循环来分配值。
# Python3 code to demonstrate working of
# Convert Coordinate Dictionary to Matrix
# Using loop + max() + list comprehension
# initializing dictionary
test_dict = { (0, 1) : 4, (2, 2) : 6, (3, 1) : 7, (1, 2) : 10, (3, 2) : 11}
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
# Convert Coordinate Dictionary to Matrix
# Using loop + max() + list comprehension
temp_x = max([cord[0] for cord in test_dict.keys()])
temp_y = max([cord[1] for cord in test_dict.keys()])
res = [[0] * (temp_y + 1) for ele in range(temp_x + 1)]
for (i, j), val in test_dict.items():
res[i][j] = val
# printing result
print("The dictionary after creation of Matrix : " + str(res))
输出 :
The original dictionary is : {(0, 1): 4, (1, 2): 10, (3, 2): 11, (3, 1): 7, (2, 2): 6}
The dictionary after creation of Matrix : [[0, 4, 0], [0, 0, 10], [0, 0, 6], [0, 7, 11]]
方法#2:使用列表推导
这是可以执行此任务的另一种方式。这执行类似于上述函数的任务,只是不同之处在于它是上述方法的简写。
# Python3 code to demonstrate working of
# Convert Coordinate Dictionary to Matrix
# Using list comprehension
# initializing dictionary
test_dict = { (0, 1) : 4, (2, 2) : 6, (3, 1) : 7, (1, 2) : 10, (3, 2) : 11}
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
# Convert Coordinate Dictionary to Matrix
# Using list comprehension
temp_x, temp_y = map(max, zip(*test_dict))
res = [[test_dict.get((j, i), 0) for i in range(temp_y + 1)]
for j in range(temp_x + 1)]
# printing result
print("The dictionary after creation of Matrix : " + str(res))
输出 :
The original dictionary is : {(0, 1): 4, (1, 2): 10, (3, 2): 11, (3, 1): 7, (2, 2): 6}
The dictionary after creation of Matrix : [[0, 4, 0], [0, 0, 10], [0, 0, 6], [0, 7, 11]]