可以使用拉姆达的列表表达式您要进行类似的操作:
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]
@ Giperboloid:该问题在答案的第二部分中得到了强调,其中使用了给定列索引的泛型“f”。 –
太棒了,但是我应该如何迭代x作为该表达式中的映射元素? – Giperboloid
你是什么意思的地图元素? 'x'是矩阵中的一个元素。 –