从变量设置* args?

时间:2015-01-16 03:09:08

标签: python function python-2.7 arguments

是否可以从变量设置*args

def fn(x, *args):
    # ...

# pass arguments not as list but each as single argument
arguments = ??? # i.e.: ['a', 'b']


fn(1, arguments)

# should be equivalent to
fn(1, 'a', 'b')

2 个答案:

答案 0 :(得分:5)

是的,你可以使用参数解包(也称为splatting):

fn(1, *arguments)

以下是演示:

>>> def fn(x, *args):
...     return args
...
>>> arguments = ['a', 'b']
>>> fn(1, *arguments)
('a', 'b')
>>>

答案 1 :(得分:0)

# pass arguments not as list but each as single argument
arguments = ??? # i.e.: ['a', 'b']

然后应该为arguments = ['a' ,'b']分配参数。这是参数解包。