"""python的拆包和封包之 *號在函數形參和實參的區別1. 在函數形參定義時添加*就是封包過程,封包預設是以元組形式進行封包2. 在函數實參調用過程添加*就是拆包過程,拆包過程中會報列表或者元組拆成單個元素"""subject = ["math", "chinese", 'english', ...
"""
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