这篇文章主要讲解了“python中元组打包和解包的过程分析”,文中的讲解内容简单清晰,易于学习与理解,下面请大家跟着小编的思路慢慢深入,一起来研究和学习“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))
感谢各位的阅读,以上就是“python中元组打包和解包的过程分析”的内容了,经过本文的学习后,相信大家对python中元组打包和解包的过程分析这一问题有了更深刻的体会,具体使用情况还需要大家实践验证。这里是亿速云,小编将为大家推送更多相关知识点的文章,欢迎关注!
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。