简体   繁体   English

从变量传递 arguments - Python

[英]Passing arguments from variable - Python

I'm writing a python script.我正在写一个 python 脚本。 In the script I wrote a function with some arguments that all has defult values.在脚本中,我写了一个 function 和一些 arguments ,它们都有默认值。 Also in the script i have list of tuples, first item in each tuple its the name of the argument from the function, the second is the value.同样在脚本中我有元组列表,每个元组中的第一项是来自 function 的参数的名称,第二项是值。 here is code for example:这是例如代码:

def f(a=0, b=0, c=0):
    print(a), print(b), print(c)

args = [('a', 12), ('c', -64)]

Is there some way, when I call the method, to put the value 12 in the 'a' argument and the value -64 in the 'c' argument without do it manualy?当我调用该方法时,是否有某种方法可以将值 12 放入“a”参数中,将值 -64 放入“c”参数中,而无需手动操作? (the value b remains 0). (值 b 保持为 0)。

Thanks for any Help!谢谢你的帮助!

You can build a dictionary then unpack it with ** :你可以建立一个字典,然后用**解压它:

f(**dict(args))

will output将 output

12
0
-64
def f(a=0, b=0, c=0):
    print(a), print(b), print(c)

args = [('a', 12), ('c', -64)]

f(**dict(args))

result:结果:

a = 12
b = 0
c = -64

But better way to use dict但更好的方式来使用 dict

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

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