将元组扩展为参数 [英] Expanding tuples into arguments
本文介绍了将元组扩展为参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
有没有办法将 Python 元组扩展为函数 - 作为实际参数?
Is there a way to expand a Python tuple into a function - as actual parameters?
例如,这里 expand()
发挥了作用:
For example, here expand()
does the magic:
some_tuple = (1, "foo", "bar")
def myfun(number, str1, str2):
return (number * 2, str1 + str2, str2 + str1)
myfun(expand(some_tuple)) # (2, "foobar", "barfoo")
我知道可以将 myfun
定义为 myfun((a, b, c))
,但当然可能会有遗留代码.谢谢
I know one could define myfun
as myfun((a, b, c))
, but of course there may be legacy code.
Thanks
推荐答案
myfun(*some_tuple)
完全符合您的要求.*
运算符简单地解包元组(或任何可迭代对象)并将它们作为位置参数传递给函数.阅读有关解包参数的更多信息.
myfun(*some_tuple)
does exactly what you request. The *
operator simply unpacks the tuple (or any iterable) and passes them as the positional arguments to the function. Read more about unpacking arguments.
这篇关于将元组扩展为参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文