【问题标题】:Passing a tuple variable as a parameter to a function将元组变量作为参数传递给函数
【发布时间】:2026-01-06 18:25:01
【问题描述】:

我希望能够将两个整数的元组的 z 变量作为参数传递给 add 函数。为了有足够的参数正常运行,我必须在函数调用中添加什么? (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

【问题讨论】:

    标签: python function tuples


    【解决方案1】:

    您实际上并不想传递一个元组(这将是 1 个参数:到更少),但您可以使用解包运算符来解包所有元组成员:

    add(*z)
    

    【讨论】: