![](/img/trans.png)
[英]Only pass an argument to a function if it takes that argument Python
[英]How to pass meshgrid as an argument to a function which only allows an array in python
I am programming in python and I want to plot a function defined by as "objFun (inputPoint, parameter2, parameter3)" with three arguments where the first argument is the point (a numpy array of 2 elements or coordinates) at which the function value被计算。 我的方法是
x = np.linspace(-10,10,50)
y = np.linspace(-10,10,50)
X,Y = np.meshgrid(x,y)
但是我不知道如何将 X 和 Y 作为 arguments 传递给 objFun,因为它接受一维变量数组。 我无法更改 function 以接受 X 和 Y 作为 arguments。 objFun 的一个示例如下:
def objFun (x, alpha, beta):
if alpha > 0 :
return x[0]^2+x[1]^2
else if beta > 0 :
return x[0] + x[1]
else:
return 0
我想将网格点 X、Y 馈送到 x[0] 和 x[1]。
更新:答案现在包括 OP 的示例 function 并显示如何传递关键字参数值。
您可以结合使用map()
和zip()
,同时使用lambda
function 构造来获取参数值:
import numpy as np
def objFun (x, alpha, beta):
"""example function by OP without default parameter values"""
if alpha > 0:
return x[0]**2 + x[1]**2
elif beta > 0:
return x[0] + x[1]
else:
return 0
x = np.linspace(-10, 10, 3) # numbers reduced to 3
y = np.linspace(-10, 10, 3) # for convenience
X,Y = np.meshgrid(x,y)
for i in map(lambda x: objFun(x, alpha=1, beta=1), zip(X.flatten(), Y.flatten())):
print(i) # just for testing/demonstration
output 符合预期:
200.0
100.0
200.0
100.0
0.0
100.0
200.0
100.0
200.0
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.