如何在函数调用中解压多个元组 [英] How to unpack multiple tuples in function call
本文介绍了如何在函数调用中解压多个元组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如果我有一个函数 def f(a, b, c, d)
和两个元组,每个元组有两个元素,有没有办法解压这些元组,以便我可以发送它们的值到函数?
f(*tup1, *tup2)
解决方案
截至 thePython 3.5.0 发布,PEP 448附加解包概括" 为这个有效的 Python 生成自然语法:
<预><代码>>>>f(*tup1, *tup2)1 2 2 3在旧版本的 Python 中,您可能需要将元组连接在一起以提供单个扩展参数:
<预><代码>>>>tup1 = 1, 2>>>tup2 = 2, 3>>>定义 f(a, b, c, d):打印(a,b,c,d)>>>f(*tup1+tup2)1 2 2 3If I have a function def f(a, b, c, d)
and two tuples, each with two elements, is there any way to unpack these tuples so that I can send their values to the function?
f(*tup1, *tup2)
解决方案
As of the release of Python 3.5.0, PEP 448 "Additional Unpacking Generalizations" makes the natural syntax for this valid Python:
>>> f(*tup1, *tup2)
1 2 2 3
In older versions of Python, you can need to concatenate the tuples together to provide a single expanded argument:
>>> tup1 = 1, 2
>>> tup2 = 2, 3
>>> def f(a, b, c, d):
print(a, b, c, d)
>>> f(*tup1+tup2)
1 2 2 3
这篇关于如何在函数调用中解压多个元组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文