在Python中缩放列表列表的列



如果我有一个矩阵作为一个简单的数组数组(而不是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]]
[[row[i]*scale if i == index else row[i] for i in range(0, len(row))] for row in mtx]

最新更新