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元組如何打包和解包內容請搜索WalkonNet以前的文章或繼續瀏覽下面的相關文章希望大傢以後多多支持WalkonNet!

推薦閱讀: