简体   繁体   English

Python 列表多重赋值

[英]Python List Multiple Assignment

How to do Python list multiple assignment in one line.如何在一行中执行 Python 列表多项赋值。

>>>a,b,c = [1,2,3]
>>> a
1
>>>b
2
>>>c
3

but what should I do to assign rest of the sub array to c但是我应该怎么做才能将子数组的其余部分分配给c

>>> a,b,c = [1,2,3,4,5,6,7,8,9] ##this gives an error but how to ..?
>>> a
1
>>>b
2
>>>c
[3,4,5,6,7,8,9]

how to do this?这该怎么做?

You can use Extended iterable unpacking : by adding * in front of c , c will catch all (rest) items. 您可以使用Extended iterable unpacking :通过在c前面添加* ,c将捕获所有(其余)项目。

>>> a, b, *c = [1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> a
1
>>> b
2
>>> c
[3, 4, 5, 6, 7, 8, 9]

first Assign the list to a like this: 首先将列表分配给如下:

a= [1,2,3,4,5,6,7,8,9]

assign second element to 'b' with: 将第二个元素分配给'b':

b=a[1]

assign rest of the elements to 'c' with: 将其余元素分配给'c':

c=a[2:9]

then reassign first element to 'a': 然后将第一个元素重新分配给'a':

a=a[0]

here we go. 开始了。 :) :)

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

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