资讯

精准传达 • 有效沟通

从品牌网站建设到网络营销策划,从策略到执行的一站式服务

python拆包和封包

"""
python的拆包和封包之 *号在函数形参和实参的区别
1. 在函数形参定义时添加*就是封包过程,封包默认是以元组形式进行封包
2. 在函数实参调用过程添加*就是拆包过程,拆包过程中会报列表或者元组拆成单个元素
"""

subject = ["math", "chinese", 'english', 'physics', 'history']


def print_subject_one(sub):
print(*sub)


def print_subject_two(*sub):
print(sub)


def print_subject_three(*sub):
print(*sub)


def print_subject_four(*sub):
print(*sub)


def print_subject_five(*sub):
print(sub)


print_subject_one(subject) # math chinese english physics history
print_subject_two(subject) # (['math', 'chinese', 'english', 'physics', 'history'],)
print_subject_three(subject) # ['math', 'chinese', 'english', 'physics', 'history']
print_subject_four(*subject) # math chinese english physics history
print_subject_five(*subject) # ('math', 'chinese', 'english', 'physics', 'history')


"""
python的拆包和封包之 **号在函数形参和实参的区别
1. 在函数形参定义时添加**就是封包过程,封包默认是字典形式进行封包,
2. 在函数实参调用过程添加**就是拆包过程,通常在存在关键字参数的函数去使用**对字典进行拆包
"""

hobby = {"jack": "dance", "henry": "basketball", "jenny": "swimming", "richard": "reading"}


def print_hobby_one(**bby):
print(bby)


def print_hobby_two(**bby):
print(bby)


def print_hobby_three(**bby):
if "jack" in bby:
print('jack like dance')
if "jenny" in bby:
print("jenny like swimming")


print_hobby_one(**hobby) # {'jack': 'dance', 'henry': 'basketball', 'jenny': 'swimming', 'richard': 'reading'}
print_hobby_two(jack='dance', henry='basketball') # {'jack': 'dance', 'henry': 'basketball'}
print_hobby_three(**hobby) # jack like dance jenny like swimming


"""
python的拆包和封包之 * 在其它场景的应用
"""

a, *_, c = [1, 2, 3, 4, 5, 6] # a=1, c=6
print(a) # a=1, c=6
print(c) # a=1, c=6


a, b, *_ = [1, 2, 3, 4, 5, 6]
print(a) # a=1
print(b) # b=2


# 一行代码搞定两个变量交换赋值
x = 10
y = 20

x, y = y, x
print(x) # x = 20
print(y) # y = 10


本文标题:python拆包和封包
分享网址:http://www.cdkjz.cn/article/dsogjid.html
多年建站经验

多一份参考,总有益处

联系快上网,免费获得专属《策划方案》及报价

咨询相关问题或预约面谈,可以通过以下方式与我们联系

大客户专线   成都:13518219792   座机:028-86922220