简体   繁体   English

将元组变量作为参数传递给 function

[英]Passing a tuple variable as a parameter to a function

I want to be able to pass the z variable of a tuple of two integers as the parameters to the add function.我希望能够将两个整数的元组的 z 变量作为参数传递给 add function。 What must I add to the function call in order to have enough parameters to run properly?为了有足够的参数正常运行,我必须在 function 调用中添加什么? (Python code) (Python代码)

def add(x, y):
    return x + y

print(add(3, 4)) # this line works just fine
z = (3, 4)
print(add(z)) # this line will cause an error

You don't actually want to pass a tuple (which would be 1 parameter: to less), but you may use the unpack operator to unpack all of the tuple members:您实际上并不想传递元组(这将是 1 个参数:传递给更少),但您可以使用 unpack 运算符解包所有元组成员:

add(*z)

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

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