在将多个以逗号分隔的值赋给一个变量时,多个值被打包成一个元组类型。当我们将一个元组赋给多个变量时,它将解包成多个值,然后分别将其赋给相应的变量。
# 打包
a = 1, 10, 100
print(type(a), a) # <class 'tuple'> (1, 10, 100)
# 解包
i, j, k = a
print(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', 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元组如何打包和解包内容请搜索编程网以前的文章或继续浏览下面的相关文章希望大家以后多多支持编程网!