编写一个 lambda 函数来计算方程,并使用 while 循环将其应用于 3x3 矩阵的每个元素
Write a lambda function to compute the equation and apply it to each element of the 3x3 matrix using a while loop
等式为 pow(x,2) - 2*x + 3,而 3x3 矩阵为 [1,2,3];[5,6,7];[4,1,6]。
我是否会使用'y=lambda x: pow(x,2)-2*x + 3,其中 x 是矩阵?我不确定如何创建将方程应用于每个元素的 while 循环
lambda 函数本身运行良好,但我不确定如何将它一次应用于一个元素。
实际上有很多方法可以做到这一点,但我只会写下一些。我假设你的矩阵是一个嵌套列表。
正如之前有人指出的那样,最易读(也许最好)的方法是使用嵌套列表理解:
mat = [[1, 2, 3], [5, 6, 7], [4, 1, 6]]
[[ele**2 - 2*ele + 3 for ele in row] for row in mat]
>> [[2, 3, 6], [18, 27, 38], [11, 2, 27]]
如果您 want/have 使用 lambda,则无需将其存储在变量中。相反,您可以在嵌套列表理解或内置 map()
函数中使用它。使用嵌套列表理解:
mat = [[1, 2, 3], [5, 6, 7], [4, 1, 6]]
[[(lambda x: x**2 - 2*x + 3)(ele) for ele in row] for row in mat]
>> [[2, 3, 6], [18, 27, 38], [11, 2, 27]]
使用map()
:
mat = [[1, 2, 3], [5, 6, 7], [4, 1, 6]]
[list(map(lambda x : x**2 - 2*x + 3, row)) for row in mat]
>> [[2, 3, 6], [18, 27, 38], [11, 2, 27]]
如果你真的想使用 while 循环,你可以使用这种非常不符合 python 的方法:
mat = [[1, 2, 3], [5, 6, 7], [4, 1, 6]]
res = []
i = 0
while i < len(mat):
res.append(list(map(lambda x : x**2 - 2*x + 3, mat[i])))
i += 1
res
>> [[2, 3, 6], [18, 27, 38], [11, 2, 27]]
等式为 pow(x,2) - 2*x + 3,而 3x3 矩阵为 [1,2,3];[5,6,7];[4,1,6]。
我是否会使用'y=lambda x: pow(x,2)-2*x + 3,其中 x 是矩阵?我不确定如何创建将方程应用于每个元素的 while 循环
lambda 函数本身运行良好,但我不确定如何将它一次应用于一个元素。
实际上有很多方法可以做到这一点,但我只会写下一些。我假设你的矩阵是一个嵌套列表。 正如之前有人指出的那样,最易读(也许最好)的方法是使用嵌套列表理解:
mat = [[1, 2, 3], [5, 6, 7], [4, 1, 6]]
[[ele**2 - 2*ele + 3 for ele in row] for row in mat]
>> [[2, 3, 6], [18, 27, 38], [11, 2, 27]]
如果您 want/have 使用 lambda,则无需将其存储在变量中。相反,您可以在嵌套列表理解或内置 map()
函数中使用它。使用嵌套列表理解:
mat = [[1, 2, 3], [5, 6, 7], [4, 1, 6]]
[[(lambda x: x**2 - 2*x + 3)(ele) for ele in row] for row in mat]
>> [[2, 3, 6], [18, 27, 38], [11, 2, 27]]
使用map()
:
mat = [[1, 2, 3], [5, 6, 7], [4, 1, 6]]
[list(map(lambda x : x**2 - 2*x + 3, row)) for row in mat]
>> [[2, 3, 6], [18, 27, 38], [11, 2, 27]]
如果你真的想使用 while 循环,你可以使用这种非常不符合 python 的方法:
mat = [[1, 2, 3], [5, 6, 7], [4, 1, 6]]
res = []
i = 0
while i < len(mat):
res.append(list(map(lambda x : x**2 - 2*x + 3, mat[i])))
i += 1
res
>> [[2, 3, 6], [18, 27, 38], [11, 2, 27]]