简体   繁体   English

如何将位置参数传递给 python 函数中的可选参数?

[英]How can I pass a positional argument to an optional argument in python functions?

I am writing a gradient descent function for linear regression and want to include a default initial guess of parameters as a numpy zero array whose length is determined by the shape of an input 2D array.我正在编写用于线性回归的梯度下降 function 并希望将参数的默认初始猜测包含为 numpy 零数组,其长度由输入二维数组的形状确定。 I tried writing the following我试着写以下

def gradient_descent(X,w0=np.zeros(X.shape[1])):

which does not work, raising an error that X is not defined in the optional argument.这不起作用,引发一个错误,即 X 未在可选参数中定义。 Is it possible to pass a positional argument to the optional argument in a python function?是否可以将位置参数传递给 python function 中的可选参数?

You could do this:你可以这样做:

def gradient_descent(X, w0=None):
  if not w0:
    w0 = np.zeros(X.shape[1])
  ...

I think you want to contain the logic into the function itself:我认为您想将逻辑包含在 function 本身中:

def gradient_descent(X, w0=None):
    if w0 == None:
        w0 = np.zeros(X.shape[1])
    #Then continue coding here

Does that make sense?那有意义吗? As a whole, you want to specify the parameters when defining the function, but not include logic.总的来说,定义function时要指定参数,但不包括逻辑。 As a concept, the logic should primarily be included into the body of the function.作为一个概念,逻辑应该主要包含在 function 的主体中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何让 argparse 识别跟随可变长度可选参数的位置参数? - How can I get argparse to recognize a positional argument which follows a variable length optional argument? 如何在argparser中基于python中的某些条件使位置参数可选 - How to make positional argument optional in argparser based on some condition in python 带有可检测开关的python argparse可选位置参数 - python argparse optional positional argument with detectable switch Python argparse-强制参数-位置或可选 - Python argparse - mandatory argument - either positional or optional Python argparse:参数的可选值和位置值 - Python argparse: both optional and positional value for an argument 每个位置参数的可选参数 - Optional argument for each positional argument 如何在可选位置参数之前定义可选参数值? - How to define optional argument value before optional positional argument? 我该如何解决 SyntaxError:位置参数跟随关键字参数 - How can I slove SyntaxError: positional argument follows keyword argument 如何将位置参数与可选参数组合? - How to combine positional argument with an optional one? Python的argparser:如何将位置参数的命令行输入设置为可选参数的默认值? - Python's argparser: how to set command line input of a positional argument as the default for an optional argument?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM