Python如何向map()函数传入矩阵行列索引实现按位置自定义运算
如何向
map()对应的处理函数传入行列索引,实现按索引规则处理矩阵元素 你可以结合enumerate()函数生成行列的索引值,再将索引与对应元素一起传入map()的处理函数即可。map()支持传入多个可迭代对象,会按位置依次将各个可迭代对象的元素传给处理函数作为参数。
完整实现代码
mtrx = [[1,0,0,0,0,0],[0,1,0,1,1,1],[0,0,1,0,1,0],[1,1,0,0,1,0],[1,0,1,1,0,0],[1,0,0,0,0,1]] # 列处理函数新增行索引x、列索引y两个入参 def colmnFun(x, y, colmn): # 可自行调整规则的优先级,示例优先级:列规则>行规则>默认规则 if y == 3: return colmn + 1 elif x == 1: return (colmn + 2) * 5 else: return colmn * 5 def rowFun(x_row): # 拆解enumerate返回的(行索引, 行内容) x, row = x_row # 向map传入3个可迭代对象:重复的行索引x、所有列索引、所有列元素 return list(map(colmnFun, [x]*len(row), range(len(row)), row)) # 先对原矩阵做enumerate生成每行的行索引 result = list(map(rowFun, enumerate(mtrx))) print(result)
运行输出
[[5, 0, 0, 1, 0, 0], [10, 15, 10, 2, 15, 15], [0, 0, 5, 1, 5, 0], [5, 5, 0, 1, 5, 0], [5, 0, 5, 2, 0, 0], [5, 0, 0, 1, 0, 5]]
更简洁的替代写法
如果不需要严格使用map(),用列表推导式的写法可读性更高,逻辑完全一致:
result = [ [colmn+1 if y==3 else (colmn+2)*5 if x==1 else colmn*5 for y, colmn in enumerate(row)] for x, row in enumerate(mtrx) ]
内容的提问来源于stack exchange,提问作者user6580267
相关产品推荐
相关产品推荐

