从列表中传递 *arg 参数
Passing *arg arguments from list
我处于必须调用一个函数 foo 的情况:
def foo(arg1,arg2,*args):
pass
问题是我在计算期间将 *args
个参数存储为列表。
像这样:
a = 'arg1'
b = 'arg2'
list_of_args = ['arg3','arg4','arg5']
如何使用此参数调用函数 foo,如下所示:
foo('arg1','arg2','arg3','arg4','arg5')
我可以这样做:
foo(a,b,list_of_args[0],list_of_args[1],list_of_args[2])
但它不能解决这个问题,因为 list_of_args
的长度取决于情况,所以它可能是:
foo(a,b,list_of_args[0],list_of_args[1],list_of_args[2],list_of_args[3],...)
只需用 *
:
解压列表
a = 'arg1'
b = 'arg2'
list_of_args = ['arg3','arg4','arg5']
foo(a, b, *list_of_args)
来自docs:
If the syntax *expression
appears in the function call, expression
must evaluate to an iterable. Elements from this iterable are treated
as if they were additional positional arguments
我处于必须调用一个函数 foo 的情况:
def foo(arg1,arg2,*args):
pass
问题是我在计算期间将 *args
个参数存储为列表。
像这样:
a = 'arg1'
b = 'arg2'
list_of_args = ['arg3','arg4','arg5']
如何使用此参数调用函数 foo,如下所示:
foo('arg1','arg2','arg3','arg4','arg5')
我可以这样做:
foo(a,b,list_of_args[0],list_of_args[1],list_of_args[2])
但它不能解决这个问题,因为 list_of_args
的长度取决于情况,所以它可能是:
foo(a,b,list_of_args[0],list_of_args[1],list_of_args[2],list_of_args[3],...)
只需用 *
:
a = 'arg1'
b = 'arg2'
list_of_args = ['arg3','arg4','arg5']
foo(a, b, *list_of_args)
来自docs:
If the syntax
*expression
appears in the function call,expression
must evaluate to an iterable. Elements from this iterable are treated as if they were additional positional arguments