Python 将矩阵转换为坐标字典
字典是四种数据类型中最受欢迎的之一,用于无序的键值对集合。Python矩阵将用于表示列表的列表,其中内部列表表示矩阵的行值。坐标字典通过给出坐标值来定义元组以设置行和列。在Python中,我们有一些内置函数,如len(),range(),zip()等,可以用来解决将矩阵转换为坐标字典的问题。
语法
下面是例子中使用的语法-
len()
len() 是 Python 中的一个内置方法,用于返回对象的长度。
range()
range()是Python中的一个内置函数,它返回给定范围之间的元素序列。默认情况下,初始范围始终从0开始,并通过分配一个特定的范围来结束。
zip()
zip()是Python中的内置函数,可用于组合两个或多个可迭代对象的元素。
enumerate()
Python 的内置函数 enumerate() 允许对一个有序的序列进行迭代,以便追踪每个索引元素。
argwhere()
argwhere()是Python中的一个内置方法,它返回非零值的元素索引。
nonzero()
非零(nonzero())是Python中的一个内置函数,可以用于找到数组的索引。
使用嵌套循环
在下面的示例中,程序使用嵌套的for循环来遍历行和列。使用if语句设置条件,即矩阵值不等于零,满足将零元素的坐标对作为键,非零元素作为值的字典。最后,使用函数返回来显示特定结果。
示例
def matrix_to_coordinate_dict(matrix):
coord_dict = {}
rows = len(matrix)
cols = len(matrix[0])
for i in range(rows):
for j in range(cols):
value = matrix[i][j]
if value != 0:
coord_dict[(i, j)] = value
return coord_dict
# Create the matrix
my_matrix = [
[0, 1, 0],
[2, 0, 3],
[0, 4, 0]
]
coord_dict = matrix_to_coordinate_dict(my_matrix)
print(coord_dict)
输出
Conversion of Matrix into Coordinate:
{(0, 1): 1, (1, 0): 2, (1, 2): 3, (2, 1): 4}
使用列表推导和enumerate()
在下面的示例中,程序使用字典推导来迭代输入矩阵。非零元素的值被添加到坐标字典中,使用行和列索引作为键。使用enumerate()函数来跟踪输入矩阵中的每个元素迭代。最后,该函数返回结果作为键(元组)和值(非零元素)的对。
示例
def matrix_to_coordinate_dict(matrix):
coord_dict = {(i, j): value for i, row in enumerate(matrix) for j, value in enumerate(row) if value != 0}
return coord_dict
# Create the matrix
my_matrix = [
[0, 1, 0],
[2, 0, 3],
[0, 4, 0]
]
coord_dict = matrix_to_coordinate_dict(my_matrix)
print("Conversion of Matrix into Coordinate:\n", coord_dict)
输出
Conversion of Matrix into Coordinate:
{(0, 1): 1, (1, 0): 2, (1, 2): 3, (2, 1): 4}
使用Numpy和zip()
在以下示例中,程序使用numpy模块,并使用np作为对象引用。然后使用递归函数根据将矩阵转化为坐标字典的条件和操作。接下来,使用字典推导式遍历输入矩阵的行和列索引。然后,函数返回一个数组作为键和非零元素作为值对的元组,并显示结果。
示例
import numpy as np
def matrix_to_coordinate_dict(matrix):
indices = np.nonzero(matrix)
coord_dict = {(i, j): matrix[i][j] for i, j in zip(indices[0], indices[1])}
return coord_dict
# Create the matrix
my_matrix = np.array([
[0, 1, 0],
[2, 0, 3],
[0, 4, 0]
])
coord_dict = matrix_to_coordinate_dict(my_matrix)
print(coord_dict)
输出
{(0, 1): 1, (1, 0): 2, (1, 2): 3, (2, 1): 4}
使用Numpy和numpy.argwhere()
在下面的示例中,程序使用numpy模块将对象引用设置为np。它使用内置函数argwhere()在矩阵中查找非零元素。在生成的字典中,键以元组的形式表示坐标,而值被设置为矩阵的非零元素。
示例
import numpy as np
# Recursive function
def matrix_to_coordinate_dict(matrix):
indices = np.argwhere(matrix != 0)
coord_dict = {(i, j): matrix[i][j] for i, j in indices}
return coord_dict
# Create the matrix
my_matrix = np.array([
[0, 1, 0],
[2, 0, 3],
[0, 4, 0]
])
# Calling function
coord_dict = matrix_to_coordinate_dict(my_matrix)
print(coord_dict)
输出
{(0, 1): 1, (1, 0): 2, (1, 2): 3, (2, 1): 4}
结论
我们讨论了在Python中将矩阵转换为坐标字典的各种方法。坐标值以元组的形式表示,其中设置了两个不同的整数。它可以应用于稀疏矩阵表示、矩阵操作和图算法等领域。