1、在將多個以逗號分隔的值賦給一個變量時,多個值被打包成一個元組類型。當(dāng)我們將一個元組賦給多個變量時,它將解包成多個值,然后分別將其賦給相應(yīng)的變量。
# 打包
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、解包時,如果解包出來的元素?cái)?shù)目與變量數(shù)目不匹配,就會引發(fā)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)
知識點(diǎn)擴(kuò)充:
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))
到此這篇關(guān)于python元組打包和解包過程詳解的文章就介紹到這了,更多相關(guān)python元組如何打包和解包內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
您可能感興趣的文章:- 一篇文章帶你了解python元組基礎(chǔ)
- Python內(nèi)置數(shù)據(jù)結(jié)構(gòu)列表與元組示例詳解
- Python基礎(chǔ)之元組與文件知識總結(jié)
- python中列表(list)和元組(tuple)的深入講解
- Python中元組的基礎(chǔ)介紹及常用操作總結(jié)