1、在将多个以逗号分隔的值赋给一个变量时,多个值被打包成一个元组类型。当我们将一个元组赋给多个变量时,它将解包成多个值,然后分别将其赋给相应的变量。
# 打包 a = 1, 10, 100 print(type(a), a) # <class 'tuple'> (1, 10, 100) # 解包 i, j, k = a print(i, j, k) # 1 10 100
2、解包时,如果解包出来的元素数目与变量数目不匹配,就会引发ValueError异常。错误信息为:too many values to unpack(解包的值太多)或not enough values to unpack(解包的值不足)。
a = 1, 10, 100, 1000 # i, j, k = a # ValueError: too many values to unpack (expected 3) # i, j, k, l, m, n = a # ValueError: not enough values to unpack (expected 6, got 4)
知识点扩充:
python之打包,解包
#coding:utf-8 #字符串,列表,元组打包与解包 aString = 'abc' aList = [1, 2, 3] aTuple = 'a', 'A', 1 print('Unpacking string......') first, second, third = aString print("string values:", first, second, third) print('\nUnpacking list......') first, second, third = aList print("string values:", first, second, third) print('\nUnpacking tuple......') first, second, third = aTuple print("string values:", first, second, third) #swapping two values x = 3 y = 4 print('\nBefore swapping: x = %d,y =%d' % (x, y)) #首先将右边的部分打包成一个元组,即(4,3),而后解包指派给变量x,y x, y = y, x #swap Variables print('After swapping: x = %d, y = %d' % (x, y)
关于“python元组打包和解包怎样实现,代码是什么”的内容今天就到这,感谢各位的阅读,大家可以动手实际看看,对大家加深理解更有帮助哦。如果想了解更多相关内容的文章,关注我们,群英网络小编每天都会为大家更新不同的知识。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:mmqy2019@163.com进行举报,并提供相关证据,查实之后,将立刻删除涉嫌侵权内容。
长按识别二维码并关注微信
更方便到期提醒、手机管理