0%

Python之Packing封包、Unpacking解包

这里介绍Python中的Packing封包、Unpacking解包

abstract.png

Packing封包

所谓封包指的是,将多个值赋值给一个变量时,Python会自动将这些值封包为一个元组

1
2
3
4
5
title = "Packing 封包"
print(f"------------ {title} -------------------")

count = 996, 123, -3
print("count:",count)

figure 1.png

Unpacking解包

序列/可迭代对象 解包

所谓 序列解包 (或可迭代对象解包)指的是:对一个序列(或可迭代对象)解包,并将得到的值存储到一系列变量中

1
2
3
4
5
6
7
title = "解包"
print(f"------------ {title} -------------------")

name1, name2, name3 = ["Tom","Aaron","Bob"]
print("name1: ", name1)
print("name2: ", name2)
print("name3: ", name3)

figure 2.png

解包的序列(或可迭代对象)包含的元素个数 必须与 等号左侧的变量数相同,否则会抛异常

1
2
3
4
5
6
7
8
9
10
11
students = {"Bob", "Aaron", "tony"}

try:
s1, s2 = students
except Exception as ex:
print("ex:",ex)

try:
s1, s2, s3, s4 = students
except Exception as ex:
print("ex:",ex)

figure 3.png

如果解包的序列(或可迭代对象)包含的元素个数 与 等号左侧的变量数 不同时,可在变量名前添加*星号,其会将多余的值以列表的形式赋值给该变量。显然存在多个*星号变量会报错

1
2
3
4
a, *b, c = (11,22,33,44,55,66)
print("a:",a)
print("b:",b)
print("c:",c)

figure 4.png

解包时如果不关心该位置的值, 可以使用占位符_下划线

1
2
3
f, _, g, _ =(11,22,33,44)
print("f:",f)
print("g:",g)

figure 5.png

需注意注意的是,进行解包时,左侧不能只有一个变量名

1
2
3
4
5
x = (11,22,33)
print("x:",x)
# 此时,可以通过*_来实现
y, *_ = (11,22,33)
print("y:",y)

figure 6.png

解包传参

  • 对于 序列对象,在实参添加 * 前缀,其会将序列对象解包为若干个元素,作为函数调用的位置实参
  • 对于 字典对象,在实参添加 ** 前缀, 其会将字典解包为若干个键值对,作为函数调用的关键字实参
1
2
3
4
5
6
7
8
9
10
11

def fun(a,b,/,c,d,*args, x,y,z,**kw):
print("a:",a,"b:",b,"c:",c,"d:",d)
print("args:", args)
print("x:",x,"y:",y,"z:",z)
print("kw:", kw)

list1 = [0,1,2,3,4]
dict1 = {"x":5,"y":6,"z":7,"u":8,"v":9}

fun(*list1, **dict1)

figure 7.png

交换变量

在其他语言中交换变量值,通常需要依赖中间变量来实现。但在Python中却可以直接交换。其中对于多变量交换时,其底层实现原理即是通过序列解包实现的

1
2
3
4
5
6
7
8
9
10
11
x,y = 100, -69
print("[before swap]", "x --> ",x, "y -->>", y)
y,x = x,y
print("[after swap]", "x --> ",x, "y -->>", y)

print("\n----------------------------------------------------")

a,b,c,d = 11,22,33,44
print("[before swap]", "a --> ",a, "b -->>", b, "c -->>", c, "d -->>", d)
a,b,c,d = b,d,a,c
print("[after swap]", "a --> ",a, "b -->>", b, "c -->>", c, "d -->>", d)

figure 8.png

zip函数

zip函数将可迭代对象作为参数,其会把各可迭代对象中对应位置的元素打包为一个元组。可将zip结果对象转换为list来查看、遍历。需要注意的是,当各可迭代对象的长度不同时,zip函数将在长度最短的可迭代对象用完时,停止打包

1
2
3
4
5
6
7
8
9
names = ["Aaron", "Tom", "Bob", "Tony"]
ages = (18,33,72)
sexs = ["man", "male","woman", "null"]

zip_result = zip(names, ages, sexs)
my_list = list(zip_result)

print("zip result:", zip_result)
print("my list:", my_list)

figure 9.png

对zip对象解包时,可在传递实参zip结果对象的前添加 * 前缀

1
2
3
4
5
6
7
8
9
names = ["Aaron", "Tom", "Bob", "Tony"]
ages = (18,33,72)
sexs = ["man", "male","woman", "null"]
zip_result = zip(names, ages, sexs)

my_name, my_age, my_sex = zip( *zip_result )
print(f"my_name : {my_name}")
print(f"my_age : {my_age}")
print(f"my_sex : {my_sex}")

figure 10.png

参考文献

  1. Python编程·第3版:从入门到实践 Eric Matthes著
  2. Python基础教程·第3版 Magnus Lie Hetland著
  3. 流畅的Python·第1版 Luciano Ramalho著
请我喝杯咖啡捏~

欢迎关注我的微信公众号:青灯抽丝