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)
知识点扩充:
pyhttp://www.cppcns.comthon之打包,解包
#coding:utf-8 #字符串,列表,元组打包与解包 aStringwww.cppcns.com = 'abc' aList = [1, 2, 3] aTuple = 'a', 'A', 1 print('Unpacking string......') first, second, third = aString pr编程客栈int("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))
到此这篇关于py编程客栈thon元组打包和解包过程详解的文章就介绍到这了,更多相关python元组如何打包和解包内容请搜索我们以前的文章或继续浏览下面的相关文章希望大家以后多多支持我们!
精彩评论