Skip to main content
 首页 » 编程设计

python之将元组传递给多参数函数

2025年05月04日22over140

这里的问题是我想将元组作为参数传递给第二个函数。之前有“重复!”的叫喊声。我已经看过一篇关于类似问题的帖子 Expanding tuples into arguments

这是我正在测试的代码:

def producer(): 
    return ('a','b') 
 
def consumer(first, second, third): 
    print first+second+third 
 
arg = producer() 
consumer(*arg, 'c') # expected abc 

这会输出错误:

There's an error in your program *** only named arguments may follow *expression 

这个有用的错误消息导致将参数顺序切换为 consumer('c', *arg),但这并不能完全解决问题,因为它将输出 'cab' 。

所以我的问题是,是否有更好的方法将元组传递给多参数函数,并保持顺序?

另外,对于奖励积分,“*”运算符的作用是什么? (这个在之前的帖子里没有说明)

请您参考如下方法:

如错误消息所述,Python 不允许您在 *arg 之后有未命名的参数。

因此,您需要显式命名third:

>>> def producer(): 
...    return ('a','b') 
... 
>>> def consumer(first, second, third): 
...    print first+second+third 
... 
>>> arg = producer() 
>>> consumer(*arg, third='c') 
abc 
>>>