p = (4,5) x, y = p print(x, y ) 结果: 4 5
data = [‘ACME‘,50,91.1,(2018,7,10)] name,shares,price,date = data print(name) print(shares) print(price) print(date) 结果: ACME 50 91.1 (2018, 7, 10) name,shares,price,(year,mon,day) = data print(name) print(shares) print(price) print(year) print(mon) print(day) 结果: ACME 50 91.1 2018 7 10
如果变量和序列元素的个数不匹配,会产生一个异常
p = (4,5) w,x,y = p print(p) 结果: w,x,y = p ValueError: not enough values to unpack (expected 3, got 2)
解压赋值可以用在任何可迭代对象上面
s = ‘Hello‘ a,s,d,f,g = s print(a) print(s) print(d) print(f) print(g) 结果: H e l l o
如果只想解压一部分,丢弃其他的值,可以使用任意变量名去占位,到时候丢掉这些变量就行了,但必须保证你选用的占位变量在其他地方没有被使用
data = [‘ACME‘,50,91.1,(2018,7,10)] _,shares,price,_ = data print(shares) print(price) 结果: 50 91.1
原文地址:https://www.cnblogs.com/wanglan/p/9289201.html
时间: 2024-10-08 15:35:00