Python拆包:就是把元组或字典中的数据单独的拆分出来,然后赋予给其他的变量。
拆包: 对于函数中的多个返回数据, 去掉元组, 列表 或者字典直接获取里面数据的过程。
一、元组拆包
案例1:
def nba_teams(team1,team2):
print(team1)
print(team2)
teams=('lakers','nets')
nba_teams(*teams)
结果
lakers
nets
案例2:
def nba_teams(team1,team2):
print(team1)
print(team2)
teams=('lakers','nets','suns','75ers')
nba_teams(*teams)
报错结果:元组拆包后的位置参数要和形式参数一一对应。
TypeError: nba_teams() takes 2 positional arguments but 4 were given
但是如果要拆多个包时:用不定长参数
案例3:
def nba_teams(*team):
print(team)
teams=['lakers','nets','suns','75ers']
nba_teams(*teams)
结果
('lakers', 'nets', 'suns', '75ers')
二、列表拆包(和元组拆包过程一致)
案例4:
def nba_teams(team1,team2):
print(team1)
print(team2)
teams=['lakers','nets']
nba_teams(*teams)
结果
lakers
nets
三、字典拆包
字典拆包:相当于把外面的 {} 丢了,再把冒号变为等号,就变成了关键字参数了(‘player1’=‘butler’,‘player2’=‘durant’,‘player3’=‘james’)
案例5
def nba_player(player1,player2,player3):
print(player1)
print(player2)
print(player3)
players={'player1':'butler','player2':'durant','player3':'james'}
nba_player(**players)
结果
butler
durent
james
案例6
def nba_player(**player):
print(player)
players={'player1':'butler','player2':'durent','player3':'james'}
nba_player(**players)
结果
{'player1': 'butler', 'player2': 'durent', 'player3': 'james'}
字典拆包:会拆成关键字参数
列表和元组拆包,是拆成位置参数。