在Python中缩放列表列表

时间:2013-07-08 15:31:39

标签: python matrix

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

print语句将分别产生:

--> [ [0,1,2],[0,1,2],[0,1,2] ]
--> [ [0,17,2],[0,17,2],[0,17,2] ]

2 个答案:

答案 0 :(得分:1)

[[row[i]*scale if i == index else row[i] for i in range(0, len(row))] for row in mtx]

答案 1 :(得分:1)

>>> [[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]]