简体   繁体   English

解包列表并将其分配给变量

[英]Unpacking list and assigning it to variable

For this code,对于这段代码,

a=[1,2,3,4,5]
print(*a)

I would get output as 1 2 3 4 5 as the list a gets unpacked.当列表a被解压时,我会得到1 2 3 4 5输出。

But what if I want to assign *a to a variable x and then print?但是如果我想将*a分配给变量x然后打印怎么办?

a=[1,2,3,4,5]
x=*a
print(x)

How to get the same output as the above code ?如何获得与上述代码相同的输出?

To get the same output from print , write x = ' '.join(str(s) for s in a) .要从print获得相同的输出,请编写x = ' '.join(str(s) for s in a) However, that is not unpacking, and there is no way to use unpacking to achieve the same result here.但是,那不是解包,这里也没有办法用解包来达到同样的效果。

The unpacking operator * can only appear in the context of function arguments or an assignment target.解包运算符*只能出现在函数参数或赋值目标的上下文中。 Your original example uses unpacking for the arguments of the print function.您的原始示例对print函数的参数使用解包。 The other way you can use unpacking is in a destructuring assignment, in which case it creates a list;使用解包的另一种方法是在解构赋值中,在这种情况下,它会创建一个列表; for example:例如:

>>> first, *rest = [1, 2, 3, 4, 5]
>>> first
1
>>> rest
[2, 3, 4, 5]

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

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