函数调用中的星号和双星号运算符是什么意思?
问题描述
*
运算符在 Python 中是什么意思,例如在 zip(*x)
或 f(**k)
之类的代码中?
What does the *
operator mean in Python, such as in code like zip(*x)
or f(**k)
?
- 在解释器内部是如何处理的?
- 它会影响性能吗?是快还是慢?
- 什么时候有用,什么时候没用?
- 应该用在函数声明还是调用中?
解决方案
单星 *
将序列/集合解包为位置参数,因此您可以这样做:
The single star *
unpacks the sequence/collection into positional arguments, so you can do this:
def sum(a, b):
return a + b
values = (1, 2)
s = sum(*values)
这将解包元组,使其实际执行为:
This will unpack the tuple so that it actually executes as:
s = sum(1, 2)
双星 **
的作用相同,只是使用字典并因此命名参数:
The double star **
does the same, only using a dictionary and thus named arguments:
values = { 'a': 1, 'b': 2 }
s = sum(**values)
你也可以组合:
def sum(a, b, c, d):
return a + b + c + d
values1 = (1, 2)
values2 = { 'c': 10, 'd': 15 }
s = sum(*values1, **values2)
将执行为:
s = sum(1, 2, c=10, d=15)
另请参阅4.7.4 - 解包参数列表部分Python 文档.
Also see section 4.7.4 - Unpacking Argument Lists of the Python documentation.
此外,您可以定义函数来接受 *x
和 **y
参数,这允许函数接受任意数量的位置和/或命名参数t 在声明中特别指定.
Additionally you can define functions to take *x
and **y
arguments, this allows a function to accept any number of positional and/or named arguments that aren't specifically named in the declaration.
例子:
def sum(*values):
s = 0
for v in values:
s = s + v
return s
s = sum(1, 2, 3, 4, 5)
或使用 **
:
def get_a(**values):
return values['a']
s = get_a(a=1, b=2) # returns 1
这可以让您指定大量可选参数,而无需声明它们.
this can allow you to specify a large number of optional parameters without having to declare them.
再一次,你可以组合:
def sum(*values, **options):
s = 0
for i in values:
s = s + i
if "neg" in options:
if options["neg"]:
s = -s
return s
s = sum(1, 2, 3, 4, 5) # returns 15
s = sum(1, 2, 3, 4, 5, neg=True) # returns -15
s = sum(1, 2, 3, 4, 5, neg=False) # returns 15
相关文章