"""
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://cxhlcq.com/article/dsogjid.html