可以使用拉姆達的列表表達式您要進行類似的操作:
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'是矩陣中的一個元素。 –