目录
本博客主要参考为北京大学陈斌老师的下一站Python
解包运算符 * 和 **
- 解包(unpacking)可以将序列或者字典的数据项展开为多个语法单位;
*alist
解包可迭代对象;**adict
解包字典。
一个尴尬的场景
- 需要打印整数列表,但不需要方括号和逗号;
alist = [12, 23, 34, 45]
print(alist)
可选解决方法
# 用迭代循环
for n in alist:
print(n, "", end="")
# 其实行末多了一个空格
# 用join
print(" ".join(str(n) for n in alist))
可迭代对象解包(*
运算符)
# *解包完美解决这个问题
# 将alist解包,把其中每个整数变为1个参数
print(*alist)
# 无论可迭代对象中包含了多少个整数
print(*range(3, 53, 3))
例子
# 坐标计算距离
pos1 = (10, 10)
pos2 = (12, 15)
# 利用复数complex来计算距离
# 略显尴尬
distance = abs(complex(pos1[0], pos1[1]) - complex(pos2[0], pos2[1]))
# 用解包就很好看
distance = abs(complex(*pos1) - complex(*pos2))
print(distance)
# 还可以这么用
alist = [10023, 34, 56, 78, 90, 23, 45, 67, 89]
# 只要第1个(学号)和最后两个数(期中和期末成绩)
id, mid, final = alist[0], alist[-2], alist[-1]
# 用解包就更优雅
id, *_, mid, final = alist
# 还可以提取中间的数据项
id, *others, mid, final = alist
print(id, mid, final)
print(f"{others=}")
字典解包(**
运算符)
# print有命名参数
print(1, 2, 3, 4, sep=",", end="#")
print("END.")
# 用字典解包来对应命名参数
config = {"sep": ",", "end": "#"}
print(1, 2, 3, 4, **config)
print("END.")
# 自定义函数
def f(x, y, z):
k = x*x + y*y + z*z
return k
print(f"{f(1, 2, 3)=}")
alist = [1, 2, 3]
print(f"{f(*alist)=}")
adict = {"x": 1, "y": 2, "z": 3}
print(f"{f(**adict)=}")
标签:迭代,Python,alist,解包,运算符,complex,print
From: https://www.cnblogs.com/coco02/p/16992892.html