元组、列表、字符串解包
my_tuple = 10,20,30,40
a,b,c,d = my_tuple
print("a =",a)
print("b =",b)
print("c =",c)
print("d =",d)
# 执行结果:
a = 10
b = 20
c = 30
d = 40
a = 100
b = 300
a , b = b , a
print(a , b) # 300 100
- 在对一个元组进行解包时,变量的数量必须和元组中的元素的数量一致
- 也可以在变量前加一个 * ,这样变量将会获取元组中所有剩余的元素
a , b , *c = my_tuple
a , *b , c = my_tuple
*a , b , c = my_tuple
print(a , b)
print('c =',c)
# 执行结果:
10 20
c = [30, 40]
*a , *b , c= my_tuple # SyntaxError: two starred expressions in assignment
此外,不光是元组可解包,列表还有字符串都可以进行解包
a , b , *c = [1, 2, 3, 4, 5, 6, 7]
a , b , *c = 'hello world'