元组作为函数参数 [英] tuples as function arguments
问题描述
tuple
在 python 中(在代码块中)由逗号定义;括号不是强制性的(在以下情况下).所以这三个都是等价的:
a tuple
in python (in a code block) is defined by the commas; the parentheses are not mandatory (in the cases below). so these three are all equivalent:
a, b = 1, 2
a, b = (1, 2)
(a, b) = 1, 2
如果我定义了一个函数
def f(a, b):
print(a, b)
这样调用就行了:
f(2, 3)
这不会:
f((2, 3))
# TypeError: f() missing 1 required positional argument: 'b'
当元组是函数参数时,python 如何区别对待元组?这里括号是必要的(我理解为什么这是这种情况,我很高兴 Python 以这种方式工作!).
how does python treat tuples differently when they are function arguments? here the parentheses are necessary (i understand why this is the case and i am happy python works this way!).
我的问题是:当元组是函数参数时,python 如何以不同的方式对待它们.
my question is: how does python treat tuples differently when they are function arguments.
推荐答案
为方便起见,Python 会根据赋值语句的需要构造一个临时元组.因此,您的所有三个赋值语句在到达数据移动时都完全相同.
For convenience, Python constructs a temporary tuple as needed for an assignment statement. Thus, all three of your assignment statements are exactly the same once they reach data movement.
函数调用不是赋值语句;这是一个参考映射.因此,语义是不同的.
A function call is not an assignment statement; it's a reference mapping. Therefore, the semantics are different.
如果您希望 Python 将元组解包为两个单独的参数,请使用 *
运算符:
If you want Python to unpack your tuple into two separate arguments, use the *
operator:
f(*(2, 3))
这篇关于元组作为函数参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!