元组的序列解包
x,y,z = (1,2,3)
print(x,y,z)
1 2 3
a_tuple = 4,5,6 #(4,5,6)
(x,y,z) = a_tuple
print(x,y,z)
4 5 6
range对象的序列解包
x,y,z,m,n = range(5)
print(x,y,z,m,n)
0 1 2 3 4
迭代对象的序列解包
x,y,z,m,n = map(str, range(5))
x,y,z,m,n
('0', '1', '2', '3', '4')
列表的序列解包
x_list = [1,2,3,4,5,6,7]
x0,x1,x2,x3,x4,x5,x6 = x_list
x5
6
x,y,z = sorted([7,32,5])
print(x,y,z)
5 7 32
字典的序列解包
dict1 = {'a':1,'b':2,'c':3}
b,c,d = dict1.items()
print(b,c,d)
('a', 1) ('b', 2) ('c', 3)
b,c,d = dict1
b,c,d
('a', 'b', 'c')
b,c,d = dict1.values()
b,c,d
(1, 2, 3)
序列解包与遍历
keys = ['x1','x2','x3','x4']
values = [1,2,3,4]
for k,v in zip(keys, values):
print(k,v)
x1 1
x2 2
x3 3
x4 4
x = ['a','b','c']
for index, x_value in enumerate(x):
print('索引{0}和x的元素{1}'.format(index,x_value))
索引0和x的元素a
索引1和x的元素b
索引2和x的元素c
dict2 = {'a':1,'b':2,'c':3}
for k,v in dict2.items():
print(k,v)
a 1
b 2
c 3
序列解包的其它用法
print(*[1,2,3,4],5,*(6,7))
1 2 3 4 5 6 7
*range(4),4
(0, 1, 2, 3, 4)
{*range(3),3,4,*(5,6,7)}
{0, 1, 2, 3, 4, 5, 6, 7}
{'x':1,**{'y':2}}
{'x': 1, 'y': 2}