Python: 数组作为函数的参数
Python: array as an argument for a function
我想知道如何在 Python 中使用数组作为函数参数。我将展示一个简短的例子:
def polynom(x, coeff_arr):
return coeff_arr[0]+ coeff_arr[1]+x +coeff_arr[2]*x**2
我显然得到了需要 2 个位置参数的错误,但是当我尝试 运行 它时给出了 4 个,谁能告诉我如何做到这一点接受只使用 (coeff_arr[i ]) 在函数的参数中?
干杯
您的问题缺少用于调用该函数的代码,但从错误中我推断您将其调用为 polynom(x, coefficient1, coefficient2, coefficient3)
。相反,您需要将系数作为列表传递:
polynom(x, [coefficient1, coefficient2, coefficient3])
或者使用解包操作符*
定义函数如下,它将把x
之后的所有位置参数作为一个列表放入coeff_arr
中:
def polynom(x, *coeff_arr):
(解包运算符也可以用在函数调用中,这与获取列表并将其元素作为位置参数传递相反:
polynom(x, *[coefficient1, coefficient2, coefficient3])
相当于
polynom(x, coefficient1, coefficient2, coefficient3)
)
我想知道如何在 Python 中使用数组作为函数参数。我将展示一个简短的例子:
def polynom(x, coeff_arr):
return coeff_arr[0]+ coeff_arr[1]+x +coeff_arr[2]*x**2
我显然得到了需要 2 个位置参数的错误,但是当我尝试 运行 它时给出了 4 个,谁能告诉我如何做到这一点接受只使用 (coeff_arr[i ]) 在函数的参数中? 干杯
您的问题缺少用于调用该函数的代码,但从错误中我推断您将其调用为 polynom(x, coefficient1, coefficient2, coefficient3)
。相反,您需要将系数作为列表传递:
polynom(x, [coefficient1, coefficient2, coefficient3])
或者使用解包操作符*
定义函数如下,它将把x
之后的所有位置参数作为一个列表放入coeff_arr
中:
def polynom(x, *coeff_arr):
(解包运算符也可以用在函数调用中,这与获取列表并将其元素作为位置参数传递相反:
polynom(x, *[coefficient1, coefficient2, coefficient3])
相当于
polynom(x, coefficient1, coefficient2, coefficient3)
)