是否可以從一個變量中設置*args
?從變量設置* 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')
是否可以從一個變量中設置*args
?從變量設置* 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')
是的,你可以使用參數拆包(也被稱爲潑灑):
fn(1, *arguments)
下面是一個演示:
>>> def fn(x, *args):
... return args
...
>>> arguments = ['a', 'b']
>>> fn(1, *arguments)
('a', 'b')
>>>
啊!一個人必須使用星號!非常好,謝謝。 – Brettetete
星號(aka,splat)根據上下文打包並解包參數。 –
# pass arguments not as list but each as single argument
arguments = ??? # i.e.: ['a', 'b']
然後參數應分配arguments = ['a' ,'b']
。這是論據拆包。
您是否嘗試過自己的建議以查看結果? –
@AnthonyForloney當然! :-) – Brettetete