任何的序列/可迭代对象可以通过赋值语句解压并赋值给多个变量。
>>> a,b,c = 'hel' >>> a 'h' >>> >>> b 'e' >>> c 'l'
>>> s_iter = iter(s) >>> a,b,c = s_iter >>> a 'h' >>> b 'e' >>> >>> c 'l'
但是前提是变量数量必须跟序列元素的个数相同。
>>> a,b,c = "hello" Traceback (most recent call last): File "<input>", line 1, in <module> ValueError: too many values to unpack (expected 3) #hello 5个去解压不行!
现在的需求是:给定一个序列,然后求其开头和最后一个,(不能使用索引!)
1 >>> a,*_,c = l 2 >>> a 3 10 4 >>> c 5 7 6 >>> _ 7 [3, 5, 6, 8, 9, 7, 5, 4, 1, 10, 20, 5, 6]