[英]Why can I not call this function using a variable as an argument in Python?
Example: 例:
def somerando(a,b,c,d):
if not a+b+c+d == 9000:
return (a+b+c+d)
somerando(1,2,3,4)
Returns: 10
返回:
10
but 但
randonumbs = [1,2,3,4]
somerando(randonumbs)
Gives the following error: 给出以下错误:
TypeError Traceback (most recent call last) in ----> 1 somerando(randonumbs)
----> 1 somerando(randonumbs)中的TypeError Traceback(最近一次呼叫最近)
TypeError: somerando() missing 3 required positional arguments: 'b', 'c', and 'd'
TypeError:somerando()缺少3个必需的位置参数:“ b”,“ c”和“ d”
your function expects 4 arguments. 您的函数需要4个参数。
randonumbs = [1,2,3,4]
is a list (of four items); randonumbs = [1,2,3,4]
是一个列表(包含四个项目); that is one argument for your function. 这是您的函数的一个参数。
you could do this: 您可以这样做:
randonumbs = [1,2,3,4]
somerando(*randonumbs)
this usage of the asterisk ( *
) is discussed in this question or in PEP 3132 . 此问题或PEP 3132中讨论了星号(
*
)的用法。
You passed randonumbs
as list, means this whole list is considered as first argument to the function somerando
您将
randonumbs
作为列表传递,这意味着整个列表都被视为somerando
函数的第一个参数
You can use somerando(*randonumbs)
. 您可以使用
somerando(*randonumbs)
。
Here, *
means pass as tuple & **
means pass as dictionary (key, value pair) if you use **
in function parameters/ arguments. 如果在函数参数/自变量中使用
**
,则*
表示作为元组传递, **
表示作为字典 (键,值对)传递。
Thank you. 谢谢。
The single-asterisk form of *args can be used as a parameter to send a non-keyworded variable-length argument list to functions, like below * args的单星号形式可用作参数,以将非关键字的可变长度参数列表发送给函数,如下所示
randonumbs = [1,2,3,4]
somerando(*randonumbs)
The double asterisk form of **kwargs is used to pass a keyworded, variable-length argument dictionary to a function. ** kwargs的双星号形式用于将关键字的变长参数字典传递给函数。
randonumbs = {'a':1, 'b':2, 'c': 3, 'd': 4}
somerando(**randonumbs)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.