gpt4 book ai didi

python - 如何对矩阵的不同列应用不同的操作?

转载 作者:太空宇宙 更新时间:2023-11-03 14:07:16 25 4
gpt4 key购买 nike

我有一个嵌套列表作为矩阵。对于它的每一列的项目,我需要应用相同的操作,但操作的参数之一取决于列,因此它是可变的,并且包含在列表中。我应该为此使用什么?

例子:

arg_list = [1,2,3]

matrix = [[1,2,3],
[1,3,5],
[6,7,2],
[1,4,2]]

减法结果:

matrix = [[0,0,0],
[0,1,2],
[5,5,-1],
[0,2,-1]]

最佳答案

您可以使用一系列lambda 表达式 来执行您想要执行的操作,例如:

operations = [lambda x:x*2,lambda x:x+1,lambda x:x//3]

所以这里我们将第一列乘以二,将第二列递增,将第三列除以三。

现在我们可以使用下面的列表理解来生成一个新的矩阵:

new_matrix = [[f(x) for f,x in zip(operations,row)] for row in matrix]

假设你的矩阵是:

matrix = [[1,2,3],
[1,3,5],
[6,7,2],
[1,4,2]]

那么 new_matrix 是:

>>> [[f(x) for f,x in zip(operations,row)] for row in matrix]
[[2, 3, 1], [2, 4, 1], [12, 8, 0], [2, 5, 0]]

或更语法上:

new_matrix = [[2,  3, 1],
[2, 4, 1],
[12, 8, 0],
[2, 5, 0]]

如果您有一个通用函数:

def f(column,x):
# ... column is the index (starting by 0)
return column+x # an example

你可以使用枚举:

new_matrix = [[f(col,x) for col,x in enumerate(row)] for row in matrix]

在你的情况下你可以这样写:

def f(column,x):
return x-arg_list[column]

关于python - 如何对矩阵的不同列应用不同的操作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42487917/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com