Skip to main content
 首页 » 编程设计

python之在 Python 中缩放列表列表的列

2024年11月01日15qlqwjy

如果我有一个矩阵作为简单的数组数组(不是 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]]