在 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 语句,它将条件设置为不等于零的矩阵值,该值满足包含零个元素作为坐标对和值对作为非零元素的键。最后,它将使用函数 return 显示具体结果。
示例
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 # 创建矩阵 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}
使用列表推导和枚举()
在下面的例子中,程序使用字典推导来迭代输入矩阵。使用行和列索引作为键,将非零元素值添加到坐标字典中。使用枚举()可以跟踪输入矩阵中存在的单个元素迭代。最后,函数将结果返回为键(元组)和值对(非零元素)。
示例
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 # 创建矩阵 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 # 创建矩阵 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 # 递归函数 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 # 创建矩阵 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}
结论
我们讨论了在 Python 中将矩阵转换为坐标字典的各种方法。坐标值以元组的形式表示,其中两个不同的整数设置在一起。有一些应用,例如稀疏矩阵表示、矩阵操作和图形算法。