简体   繁体   English

从列表传递* arg参数

[英]Passing *arg arguments from list

I'm in a situation when I have to call one function foo: 我处于必须调用一个函数foo的情况:

def foo(arg1,arg2,*args):
    pass

The problem is that I have the *args arguments stored during computing as a list. 问题是我在计算过程中将*args参数存储为列表。

Like this: 像这样:

a = 'arg1'
b = 'arg2'
list_of_args = ['arg3','arg4','arg5']  

How can I call the function foo with this arguments to be like: 我如何用这个参数调用函数foo像这样:

foo('arg1','arg2','arg3','arg4','arg5')

I could do this: 我可以这样做:

foo(a,b,list_of_args[0],list_of_args[1],list_of_args[2])

but it does not solve this problem because length of list_of_args depends on a situation so it could be: 但它不能解决此问题,因为list_of_args长度取决于情况,因此可能是:

foo(a,b,list_of_args[0],list_of_args[1],list_of_args[2],list_of_args[3],...)

Simply unpack the list with * : 只需使用*打开列表:

a = 'arg1'
b = 'arg2'
list_of_args = ['arg3','arg4','arg5']

foo(a, b, *list_of_args)

From the docs : 文档

If the syntax *expression appears in the function call, expression must evaluate to an iterable. 如果语法*expression出现在函数调用中,则expression必须求值为可迭代。 Elements from this iterable are treated as if they were additional positional arguments 可迭代的元素被视为附加的位置参数

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM