简体   繁体   English

python3中的扩展序列解包

[英]Extended sequence unpacking in python3

I create a list as: 我创建一个列表:

>>> seq = [1, 2, 3, 4]

Now i assign the variables as follows: 现在我分配变量如下:

>>> a, b, c, d, *e = seq
>>> print(a, b, c, d, e)

I get output as: 我输出为:

>>> 1 2 3 4 []

Now i change the sequence in which i assign variables as: 现在我改变我将变量赋值为的顺序:

>>> a, b, *e, c, d = seq
>>> print(a, b, c, d, e)

I get output as: 我输出为:

>>> 1, 2, 3, 4, []

So my question is Why *e variable above is always assigned an empty list regardless of where it appears? 所以我的问题是为什么*上面的变量总是被分配一个空列表而不管它出现在哪里?

In the first case 在第一种情况下

a, b, c, d, *e = seq

since the sequence has only four elements, a , b , c and d get all of them and the rest of them will be stored in e . 由于序列只有四个元素, abcd得到所有元素,其余的将存储在e As nothing is left in the sequence, e is an empty list. 由于序列中没有任何内容, e是一个空列表。

In the second case, 在第二种情况下,

a, b, *e, c, d = seq

First two elements will be assigned to a and b respectively. 前两个元素将分别分配给ab But then we have two elements after the *e . 但是在*e之后我们有两个元素。 So, the last two elements will be assigned to them. 因此,最后两个元素将分配给它们。 Now, there is nothing left in the seq . 现在, seq没有任何东西了。 That is why it again gets an empty list. 这就是为什么它再次得到一个空列表。

It was a design choice, according to PEP 3132 (with my bold): 根据PEP 3132 (我的大胆),这是一个设计选择:

A tuple (or list) on the left side of a simple assignment (unpacking is not defined for augmented assignment) may contain at most one expression prepended with a single asterisk (which is henceforth called a "starred" expression, while the other expressions in the list are called "mandatory"). 简单赋值左侧的元组(或列表)(未为扩充赋值定义解包)最多可包含一个前缀为单个星号的表达式(此后称为“已加星标”的表达式,而其他表达式则为该列表被称为“强制”)。 This designates a subexpression that will be assigned a list of all items from the iterable being unpacked that are not assigned to any of the mandatory expressions , or an empty list if there are no such items. 这指定一个子表达式,该子表达式将被分配一个列表, 其中包含未被分配给任何强制性表达式的可迭代迭代的所有项目,或者如果没有这样的项目,则为空列表。

Indeed, the first example in the PEP illustrates your point: 实际上,PEP中的第一个例子说明了你的观点:

>>> a, *b, c = range(5)
>>> a
0
>>> c
4
>>> b
[1, 2, 3]
a, b, *e, c, d = [1, 2, 3, 4]

*e says "what's left put into e ". *e说:“还剩下些什么投入e ”。 Because you have 4 elements, empty sequence is put into e . 因为你有4个元素,所以将空序列放入e

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM