[英]Why does starred assignment produce lists and not tuples?
In python, I can write something like this:在python中,我可以写这样的东西:
some_list = [(1, 2, 3), (3, 2, 1)]
for i, *args in some_list:
print(args)
I will get the next output:我会得到下一个输出:
[2, 3]
[2, 1]
When we use *args
as function arguments, it is unpacked into a tuple
.当我们使用
*args
作为函数参数时,它被解包成一个tuple
。
Why do we receive a list
in this situation?为什么在这种情况下我们会收到一份
list
?
It is just a design decision.这只是一个设计决定。 Making it a
tuple
was debated in the PEP 3132 , but rejected on usability grounds:在PEP 3132中对将其
tuple
进行了辩论,但以可用性为由予以拒绝:
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 一致,但会使结果的进一步处理更加困难。
Simlarly, making it of the same type as the iterable on the rhs of the assignment, was rejected:同样,使其与赋值的 rhs 上的可迭代类型相同,也被拒绝:
Try to give the starred target the same type as the source iterable, for example, b in a, *b = 'hello' would be assigned the string 'ello'.
尝试为加星标的目标提供与源可迭代对象相同的类型,例如,a 中的 b,*b = 'hello' 将被分配字符串 'ello'。 This may seem nice, but is impossible to get right consistently with all iterables.
这可能看起来不错,但不可能与所有可迭代对象保持一致。
The very example of yours is listed in the same PEP under specification .您的示例列在规范下的同一 PEP 中。
Some reasoning is found in the mailing list of that debate.在该辩论的邮件列表中可以找到一些推理。
When dealing with an iterator, you don't know the length in advance, so the only way to get a tuple would be to produce a list first and then create a tuple from it.
在处理迭代器时,您事先不知道长度,因此获取元组的唯一方法是先生成一个列表,然后从中创建一个元组。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.