这篇文章主要讲解了“python中元组打包和解包的过程分析”,文中的讲解内容简单清晰,易于学习与理解,下面请大家跟着小编的思路慢慢深入,一起来研究和学习“python中元组打包和解包的过程分析”吧!
在将多个以逗号分隔的值赋给一个变量时,多个值被打包成一个元组类型。当我们将一个元组赋给多个变量时,它将解包成多个值,然后分别将其赋给相应的变量。
# 打包a = 1, 10, 100print(type(a), a) # <class 'tuple'> (1, 10, 100)# 解包i, j, k = aprint(i, j, k) # 1 10 100
解包时,如果解包出来的元素数目与变量数目不匹配,就会引发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', 1print('Unpacking string......')first, second, third = aStringprint("string values:", first, second, third)print('\nUnpacking list......')first, second, third = aListprint("string values:", first, second, third)print('\nUnpacking tuple......')first, second, third = aTupleprint("string values:", first, second, third)#swapping two valuesx = 3y = 4print('\nBefore swapping: x = %d,y =%d' % (x, y))#首先将右边的部分打包成一个元组,即(4,3),而后解包指派给变量x,yx, y = y, x #swap Variablesprint('After swapping: x = %d, y = %d' % (x, y))
感谢各位的阅读,以上就是“python中元组打包和解包的过程分析”的内容了,经过本文的学习后,相信大家对python中元组打包和解包的过程分析这一问题有了更深刻的体会,具体使用情况还需要大家实践验证。这里是编程网,小编将为大家推送更多相关知识点的文章,欢迎关注!