序列解包是Python语言赋值语句的一种技巧和方法
>>> x,y,z='a','b','c'
>>> x
'a'
>>> y
'b'
>>> z
'c'
>>> x,y='a','b','c'
Traceback (most recent call last):
File "" , line 1, in <module>
x,y='a','b','c'
ValueError: too many values to unpack (expected 2)
>>> x,y,z='a','b'
Traceback (most recent call last):
File "" , line 1, in <module>
x,y,z='a','b'
ValueError: not enough values to unpack (expected 3, got 2)
>>> x='a','b','c' #x实际上得到一个元组
>>> x
('a', 'b', 'c')
>>> x,y,z=['a','b','c']
>>> print(x,y,z)
a b c
>>> x,y,z=sorted([22,33,11]) #sorted([22,33,11])的结果是排好序的列表
>>> print(x,y,z)
11 22 33
>>> x='a','b','c' #x实际上得到一个元组
>>> x
('a', 'b', 'c')
>>> i,j,k=x #x是一个元组,这个元组可以进一步赋值到多个变量上
>>> print(i,j,k)
a b c
>>> s = {'Lily':165, 'Tom':177, 'Mary':168}
>>> height1,height2,height3=s.values() #s.values()是由字典的value组成的可迭代对象
>>> print(height1,height2,height3)
165 177 168
>>> name1,name2,name3=s.keys() #s.keys()是由字典的key组成的可迭代对象
>>> print(name1,name2,name3)
Lily Tom Mary
>>> name1,name2,name3=s #实际上是对字典的key所组成的可迭代对象解包
>>> print(name1,name2,name3)
Lily Tom Mary
>>> s.popitem()
('Mary', 168)
>>> name,height = s.popitem() #s.popitem()返回一个元组,再赋值到多个变量上
>>> print(name,height)
Tom 177
>>> x,y,z='abc' #字符串的序列解包
>>> print(x,y,z)
a b c
>>> x,y,z=range(1,10,4) #range对象的序列解包
>>> print(x,y,z)
1 5 9
>>> x,y,z=iter(['a','b','c']) #迭代器对象的序列解包
>>> print(x,y,z)
a b c
>>> x,y=enumerate(['abc',28]) # enumerate对象的序列解包
>>> x
(0, 'abc')
>>> y
(1, 28)
>>> print(x,y)
(0, 'abc') (1, 28)
>>> x,y=zip(['a','b'],[1,2]) # zip对象的序列解包
>>> print(x,y)
('a', 1) ('b', 2)
>>> x,y=map(int,['45','67']) # map对象的序列解包
>>> print(x,y)
45 7
>>> x,y=44,55
>>> y,x=x,y
>>> print(x,y)
55 44
>>> a=list(range(5))
>>> a
[0, 1, 2, 3, 4]
>>> a[1:4]=map(str,[11,22,33])
>>> a
[0, '11', '22', '33', 4]
>>> names=['Lily','Tom','Mary']
>>> height=[165,177,168]
>>> for i,j in zip(names,height):
print(i,j,end=' ')
Lily 165 Tom 177 Mary 168