问题描述
例如,考虑
squares = *map((2).__rpow__, range(5)),
squares
# (0, 1, 4, 9, 16)
*squares, = map((2).__rpow__, range(5))
squares
# [0, 1, 4, 9, 16]
因此,在所有其他条件相同的情况下,我们在使用lhs时会得到一个列表,而在使用rhss时会得到一个元组.
为什么?
这是设计使然吗,如果是,原因是什么?或者,如果没有,是否有任何技术原因?还是只是这样,没有特殊原因?
在RHS上获取元组的事实与splat无关.脚本会解压缩您的map
迭代器.您将其装入的方式是由您使用元组语法决定的:
*whatever,
代替列表语法:
[*whatever]
或设置语法:
{*whatever}
您本可以得到一个列表或一组.您只是告诉Python创建一个元组.
在LHS上,分散的分配目标始终会产生一个列表.是否使用元组样式"都没关系
*target, = whatever
或列表样式"
[*target] = whatever
目标列表的
语法.语法看起来很像创建列表或元组的语法,但是目标列表语法是完全不同的东西.
PEP 3132 中介绍了您在左侧使用的语法. >,以支持诸如
之类的用例first, *rest = iterable
在拆箱任务中,将iterable的元素按位置分配给未加星标的目标,如果有加星标的目标,则将所有多余内容填充到列表中并分配给该目标. 选择了一个列表而不是一个元组,以使进一步处理变得容易.由于您的示例中只有 个已加星标的目标,因此所有项目都位于分配给该目标的附加"列表中.
Consider, for example,
squares = *map((2).__rpow__, range(5)),
squares
# (0, 1, 4, 9, 16)
*squares, = map((2).__rpow__, range(5))
squares
# [0, 1, 4, 9, 16]
So, all else being equal we get a list when splatting on the lhs and a tuple when splatting on the rhs.
Why?
Is this by design, and if yes, what's the rationale? Or, if not, are there any technical reasons? Or is this just how it is, no particular reason?
The fact that you get a tuple on the RHS has nothing to do with the splat. The splat just unpacks your map
iterator. What you unpack it into is decided by the fact that you've used tuple syntax:
*whatever,
instead of list syntax:
[*whatever]
or set syntax:
{*whatever}
You could have gotten a list or a set. You just told Python to make a tuple.
On the LHS, a splatted assignment target always produces a list. It doesn't matter whether you use "tuple-style"
*target, = whatever
or "list-style"
[*target] = whatever
syntax for the target list. The syntax looks a lot like the syntax for creating a list or tuple, but target list syntax is an entirely different thing.
The syntax you're using on the left was introduced in PEP 3132, to support use cases like
first, *rest = iterable
In an unpacking assignment, elements of an iterable are assigned to unstarred targets by position, and if there's a starred target, any extras are stuffed into a list and assigned to that target. A list was chosen instead of a tuple to make further processing easier. Since you have only a starred target in your example, all items go in the "extras" list assigned to that target.
这篇关于为什么splatting在rhs上创建一个元组,而在lhs上创建一个列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!