[英]Why does python treat asterisk differently in functions and expressions?
In the following codes there are two places which asterisk(*) is used : 在以下代码中,有两个地方使用星号(*):
Asterisk in function: 星号功能:
def function(*asterisk):
print(1, type(asterisk))
Asterisk in expressions: 表达式中的星号:
a, *b = (1, 2, 3)
print(2, type(b))
a, *b = [1, 2, 3]
print(3, type(b))
I know the meaning of asterisk in functions and how it works. 我知道星号在函数中的含义及其工作原理。
My question is why asterisk in print number 1 has a tuple type whereas in print number 2 and 3 has a list type ? 我的问题是为什么打印编号1中的星号具有元组类型,而打印编号2和3中的星号具有列表类型?
Why python interprets function *parameter as tuple regardless of argument's type and interprets *variable as list regardless of assigned numbers' type in expressions? 为什么python将函数*参数解释为元组而不管参数的类型如何并将*变量解释为列表而不管表达式中指定的数字类型如何?
In the end, are those * different operators?! 最后,那些*不同的运营商?!
The devs just figured a list would be easier to process in the assignment case. 开发人员只是想出一个列表在分配案例中更容易处理。 Quoting the PEP for
a, *b = ...
syntax: 引用PEP获取
a, *b = ...
语法:
After a short discussion on the python-3000 list [1] , the PEP was accepted by Guido in its current form.
在对python-3000列表[1]进行简短讨论之后,Pido被Guido以其当前形式接受。 Possible changes discussed were:
讨论的可能变化是:
...
...
Make the starred target a tuple instead of a list.
使加星标的目标成为元组而不是列表。 This would be consistent with a function's *args, but make further processing of the result harder.
这与函数的* args一致,但更难以进一步处理结果。
And the mailing list discussion : 和邮件列表讨论 :
IMO, it's likely that you would like to further process the resulting sequence, including modifying it.
IMO,您可能希望进一步处理生成的序列,包括修改它。
The mailing list discussion is pretty short ( starts here , only 28 messages), so don't be afraid to read the whole thing. 邮件列表讨论很短( 从这里开始 ,只有28条消息),所以不要害怕阅读整个事情。
The unpacking in assignment (python 3 specific) is extended iterable unpacking (when the unpacking term refers to the right hand side , the variable that follows *
in the left hand side isn't unpacked, but created ), whereas the other one (also available in python 2) is just positional argument unpacking. 赋值中的解包(特定于python 3)是扩展的可迭代解包 (当解包术语指向右侧时 ,左侧的
*
后面的变量未解包,但是已创建 ),而另一个(也是在python中可用2)只是位置参数解包。
The *
"operator" is very different in both cases. *
“运算符”在两种情况下都非常不同。 The fact that extended iterable unpacking creates a list
is probably designed so the caller can extend that list. 扩展可迭代解包创建
list
的事实可能是设计的,因此调用者可以扩展该列表。
In parameter unpacking, it's better to have a fixed iterable like tuple
. 在参数解包中,最好有一个像
tuple
一样的固定迭代。 Once again those are completely different mechanisms. 这些是完全不同的机制。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.