*a, b, c = line.split() 中的星号有什么作用? [英] What does the asterisk do in *a, b, c = line.split()?
问题描述
假设 line
是:"Chicago Sun 01:52"
.
*a, b, c = line.split()
有什么作用?特别是星号的意义是什么?
What does *a, b, c = line.split()
do? In particular, what is the significance of the asterisk?
经过测试,似乎"Chicago"
、"Sun"
和"01:52"
都存储在a
、b
和 c
.星号似乎导致 "Chicago"
作为列表的第一个元素存储在 a 中.所以,我们有 a = ["Chicago"]
、b = "Sun"
和 c = "01:52"
.在这种情况下,有人可以指出有关星号运算符功能的材料吗?
Upon testing it, it seems like "Chicago"
, "Sun"
and "01:52"
are all stored in a
, b
and c
. The asterisk seems to lead to "Chicago"
being stored in a as the first element of a list. So, we have a = ["Chicago"]
, b = "Sun"
and c = "01:52"
. Could anyone point to material on the functionality of the asterisk operator in this situation?
推荐答案
用空格分割文本会给你:
Splitting that text by whitespace will give you:
In [743]: line.split()
Out[743]: ['Chicago', 'Sun', '01:52']
现在,这是一个 3 元素 list
.赋值将把输出的最后两个元素分别赋值给 b
和 c
.*
或 splat 运算符将把该列表的其余部分传递给 a
,因此 a
是元素列表.在这种情况下,a
是一个单元素列表.
Now, this is a 3 element list
. The assignment will take the last two elements of the output and assign them to b
and c
respectively. The *
, or the splat operator will then pass the remainder of that list to a
, and so a
is a list of elements. In this case, a
is a single-element list.
In [744]: *a, b, c = line.split()
In [745]: a
Out[745]: ['Chicago']
In [746]: b
Out[746]: 'Sun'
In [747]: c
Out[747]: '01:52'
查看 PEP 3132 和 python 的 splat 运算符 * 和 ** 在哪里有效? 有关 splat 运算符的更多信息,它们如何工作以及它们适用的地方.
Look at PEP 3132 and Where are python's splat operators * and ** valid? for more information on the splat operators, how they work and where they're applicable.
这篇关于*a, b, c = line.split() 中的星号有什么作用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!