亲宝软件园·资讯

展开

python元组如何打包和解包 python元组打包和解包过程详解

小妮浅浅 人气:0
想了解python元组打包和解包过程详解的相关内容吗,小妮浅浅在本文为您仔细讲解python元组怎样打包和解包的相关知识和一些Code实例,欢迎阅读和指正,我们先划重点: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))

加载全部内容

相关教程
猜你喜欢
用户评论