在这篇文章中我们来了解一下“Python中元组打包和解包如何做,有什么要注意的”,一些朋友可能会遇到这方面的问题,对此在下文小编向大家来讲解一下,内容详细,易于理解,希望大家阅读完这篇能有收获哦,有需要的朋友就往下看吧!
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))
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:mmqy2019@163.com进行举报,并提供相关证据,查实之后,将立刻删除涉嫌侵权内容。
长按识别二维码并关注微信
更方便到期提醒、手机管理