用Python将变量列表作为函数的位置参数添加进去。

huangapple go评论59阅读模式
英文:

python add a list of variables as positional arguments for functions

问题

我有一个需要传递给几个函数的变量列表,这些函数需要相同数量的参数。

a = 1
b = 'hello'
c = 1.9

args = (a, b, c)

op = func_a(args) if <cond1> else func_b(args)

def func_a(a, b, c):
    ...
    
def func_b(a, b, c):
    ...

但是将这个作为元组发送,元组会被设置为参数 a,而函数还期望参数 bc

我如何分别将这个元组传递为 abc

英文:

I have a list of variables that need to be passed in a couple of functions that take the same number of arguments.

a = 1
b = &#39;hello&#39;
c = 1.9

args = (a, b, c)

op = func_a(args) if &lt;cond1&gt; else func_b(args)

def func_a(a, b, c):
    ...
    
def func_b(a, b, c):
    ...

But sending this as a tuple, the tuple is set to arg a and the function expects args b and c as well.

How can I pass these tuple as a, b, and crespectively?

答案1

得分: 1

使用 * 来解包元组:

op = func_a(*args) if <cond1> else func_b(*args)

这将解包元组并将参数作为单独的参数传递。

英文:

Use * to unpack the tuple:

op = func_a(*args) if &lt;cond1&gt; else func_b(*args)

This will unpack the tuple and pass the parameters as separate arguments.

huangapple
  • 本文由 发表于 2023年2月6日 20:08:25
  • 转载请务必保留本文链接:https://go.coder-hub.com/75361122.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定