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

标签 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

打印语句将分别产生:

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

相关文章:

matrix - 快速可视化一个大的二进制矩阵?

python - numpy 行对行差异平方和,无需 for 循环(仅 api 调用)

python - 将子进程输出缓冲到文件 : io. 不支持的操作:fileno

python - 将项目添加到列表的字典中

python - 在 PyObjC 中实现 openFile 的 NSApplication 委托(delegate)协议(protocol)

c - 矩阵和 vector 相乘,逻辑错误

python - 对 glPerspective 和 GL_POLYGON 的困惑

python - 安装 cx_Freeze

c - 使用函数和双指针编写一个程序来查找给定矩阵是否为空?

r - 获取距离矩阵单元格的标签