如果我有一个简单的数组数组(不是 numpy 矩阵)的矩阵,如何仅用一行代码缩放矩阵的一列?
这只是出于好奇 - 我并不是说一行比两行或三行有任何好处。
这是我所拥有的,对于一些矩阵“mtx”、列索引“index”和标量“scale”。我们可以让它更漂亮或更易读吗?此外,如果多个列具有相同的值,这可能会失败。
mtx = zip( * ( (map(lambda r : r*scale if zip(*mtx).index(col)==index else r, col)) for col in zip(*mtx)] ) )
编辑:
这是根据要求输入/输出的示例
mtx = [ [ i for i in range(3) ] for j in range(3) ]
index = 1
scale = 17
print mtx
mtx = zip( * ( p (map(lambda r : r*scale if zip(*mtx).index(col)==index else r, col)) for col in zip(*mtx)] ) )
print mtx
打印语句将分别产生:
--> [ [0,1,2],[0,1,2],[0,1,2] ]
--> [ [0,17,2],[0,17,2],[0,17,2] ]
最佳答案
>>> [[j*((i==index)*(scale-1)+1) for i,j in enumerate(l)] for l in mtx]
[[0, 17, 2], [0, 17, 2], [0, 17, 2]]
关于python - 在 Python 中缩放列表列表的列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17530495/