如何用for循环自动生成5倍数阶矩阵标签及嵌套函数n的定义
适配5的倍数阶矩阵的标签映射解决方案
问题描述
现有一段Python代码,仅能实现5x5矩阵的元素位置映射,行、列标签为U、Lf、Ls、I、R。希望优化代码,使其自动适配10x10、15x15等5的倍数阶矩阵,自动生成带编号的标签(如U_1、Lf_1,后续为U_2、Lf_2等)。尝试嵌套函数实现,但不清楚如何定义参数n。
原始代码:
def get_addresses(i,j): # Create the matrix matrix = np.zeros((i,j)) # Define the row and column labels row_labels = ['U', 'Lf', 'Ls', 'I', 'R'] col_labels = ['U', 'Lf', 'Ls', 'I', 'R'] # Create a dictionary to map labels to indices #the keys are tuples of row and column labels #the values are tuples of row and column indices #first element of the tuple represents the row index #second element represents the column index index_map = {(row_labels[i], col_labels[j]): (i, j) for i in range(matrix.shape[0]) for j in range(matrix.shape[1])} return index_map
用户修改后的未完成代码:
def get_addresses(i,j): # Create the matrix matrix = np.zeros((i,j)) def make_rl(n): row_labels_base = ['U', 'Lf', 'Ls', 'I', 'R'] row_labels = row_labels_base[:] col_labels = row_labels_base[:] for i in range((n-1)): row_labels += ["%s%d" % (lbl,i+1) for lbl in row_labels_base] col_labels += ["%s%d" % (lbl,i+1) for lbl in row_labels_base] return row_labels, col_labels # Create a dictionary to map labels to indices #the keys are tuples of row and column labels #the values are tuples of row and column indices #first element of the tuple represents the row index #second element represents the column index index_map = {(row_labels[i], col_labels[j]): (i, j) for i in range(matrix.shape[0]) for j in range(matrix.shape[1])} return index_map
解决方案
1. 参数n的定义
n代表标签分组的数量,等于矩阵阶数除以5(每组对应5行/列)。例如:
- 5x5矩阵 →
n=1 - 10x10矩阵 →
n=2 - 15x15矩阵 →
n=3
无需手动传入n,可在函数内部通过矩阵行数i自动计算:n = i // 5(因矩阵是5的倍数,整除即可)。
2. 修正后的完整代码
import numpy as np def get_addresses(i, j): # 校验矩阵维度:必须是5的倍数且行列数相等 if i != j or i % 5 != 0: raise ValueError("矩阵必须是5的倍数阶方阵(如5x5、10x10)") matrix = np.zeros((i, j)) n = i // 5 # 自动计算分组数 def make_rl(n_groups): row_labels_base = ['U', 'Lf', 'Ls', 'I', 'R'] row_labels = [] col_labels = [] # 生成所有分组的标签:第一组无编号,后续组带_1、_2后缀 for k in range(n_groups): if k == 0: row_labels.extend(row_labels_base) col_labels.extend(row_labels_base) else: row_labels.extend([f"{lbl}_{k}" for lbl in row_labels_base]) col_labels.extend([f"{lbl}_{k}" for lbl in row_labels_base]) return row_labels, col_labels # 调用生成标签的函数 row_labels, col_labels = make_rl(n) # 生成索引映射字典 index_map = {(row_labels[x], col_labels[y]): (x, y) for x in range(matrix.shape[0]) for y in range(matrix.shape[1])} return index_map
3. 关键优化点
- 自动计算分组数:通过
n = i //5避免手动传参,减少操作成本。 - 标签格式修正:使用
f"{lbl}_{k}"生成U_1、Lf_2这类符合需求的标签。 - 变量名冲突解决:把嵌套函数内的循环变量从
i改为k,避免和外层函数的矩阵行数参数i重名。 - 维度校验:添加
ValueError校验,确保输入的矩阵是5的倍数阶方阵,避免错误。
4. 调用示例
# 生成10x10矩阵的索引映射 map_10x10 = get_addresses(10, 10) print(map_10x10[('U_1', 'Lf_1')]) # 输出(5,6),对应第6行第7列(索引从0开始) # 生成15x15矩阵的索引映射 map_15x15 = get_addresses(15, 15) print(map_15x15[('R_2', 'I_2')]) # 输出(14,12)
内容的提问来源于stack exchange,提问作者Landon
相关产品推荐
相关产品推荐

