我们以元组为例,看一下python中的拆包和装包,先上代码:
#拆包 t1 = (4,7,3) #a,b =t1 #ValueError: too many values to unpack (expected 2) #X,Y,Z = (6,) #ValueError: not enough values to unpack(expected 3,got 1) a,b,c = t1 print(a,b,c) a = t1 print(a) #变量个数与元组个数不一致(元组元素多,赋值需要的少) t1 =(2,5,8,9,7) a,*_,c = t1 print(a,c,_) a,c,*_ = t1 print(a,c,_) a,b,*c = t1 print(a,b,c) t1 = (9,568,3) a,*b=t1 print(a,b) # *b 表示未知个数0-n,0--->[] 多个元素的话--->[1,2,3,4,5,6,..] print(*b) # ''' 字符串 是否也可以使用*来拆包 列表 是否也可以使用*来拆包 x,y,*z='hello' print(x,y,z) x,*y = 'h' print(x,y) list1=[2,1,3,6,9,8] list2=[2] a,b,*_ = list1 a,*b = list2 print(a,b) ''' list1=[1,2,3,6,9] print(*list1) t3 = (9,) x,*y = t3 print(x,y) #添加元素 y.append('a') y.append('b') print(y) #['a','b'] print(*y) #拆包 t1 = (4,7,3) #a