【发布时间】:2019-04-22 03:18:37
【问题描述】:
对于我正在处理的脚本,我想让它成为可选的,以将数组传递给函数。我尝试执行此操作的方法是将有问题的变量 (residue) 设为kwarg。
问题是,当我以这种方式执行此操作时,python 将 kwarg 的 de dtype 从numpy.ndarray 更改为dict。最简单的解决方案是将变量转换回np.array,使用:
residue = np.array(residue.values())
但我不认为这是一个非常优雅的解决方案。所以我想知道是否有人可以向我展示一种“更漂亮”的方式来实现这一点,并可能向我解释为什么 python 会这样做?
有问题的函数是:
#Returns a function for a 2D Gaussian model
def Gaussian_model2D(data,x_box,y_box,amplitude,x_stddev,y_stddev,theta,**residue):
if not residue:
x_mean, y_mean = max_pixel(data) # Returns location of maximum pixel value
else:
x_mean, y_mean = max_pixel(residue) # Returns location of maximum pixel value
g_init = models.Gaussian2D(amplitude,x_mean,y_mean,x_stddev,y_stddev,theta)
return g_init
# end of Gaussian_model2D
使用以下命令调用该函数:
g2_init = Gaussian_model2D(cut_out,x_box,y_box,amp,x_stddev,y_stddev,theta,residue=residue1)
我使用的 Python 版本是 2.7.15
【问题讨论】:
-
可选参数不是这样工作的。
-
def Gaussian_model2D(data, x_box, y_box, amplitude, x_stddev, y_stddev, theta, residue=None): -
dtype不能是dict... -
使
residue成为一个可选 参数,类似于def foo(residue=None)然后检查if residue is not None: ... do stuff with residue -
使用
residue = None编译时出现以下错误:ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
标签: python python-2.7 dictionary keyword-argument numpy-ndarray