问题描述
例如,考虑
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.
为什么?
这是设计使然,如果是,其基本原理是什么?或者,如果没有,是否有任何技术原因?还是就是这样,没有什么特别的原因?
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?
推荐答案
你在 RHS 上得到一个元组的事实与 splat 无关.splat 只是解压缩您的 map
迭代器.你将它解压成什么取决于你使用了元组语法:
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,
而不是列表语法:
[*whatever]
或设置语法:
{*whatever}
你可以得到一个列表或一组.你刚刚告诉 Python 创建一个元组.
You could have gotten a list or a set. You just told Python to make a tuple.
在 LHS 上,一个 splatted 分配目标总是产生一个列表.是否使用元组样式"都没关系
On the LHS, a splatted assignment target always produces a list. It doesn't matter whether you use "tuple-style"
*target, = whatever
或列表样式"
[*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.
您在左侧使用的语法是在 PEP 3132,支持用例,如
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 上创建一个列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!