我有一个函数,它接受一个位置参数、一个默认参数、可变长度非关键字参数和可变长度关键字参数。该函数如下所示:
def set_football_team(name,
coach = '',
*players, **formations):
print("Team: "+name)
print("Coach: "+coach)
for i, player in enumerate(players):
print("Player "+str(i+1)+": "+player)
for position, positional_players in formations.items():
positional_players = ", ".join(positional_players)
print(position+": "+positional_players)
当所有参数都被传递时,它工作正常。
name = "Real Madrid"
coach = "Zinedine Zidane"
players = ["Keylor Navas", "K. Casilla",
"Sergio Ramos", "Varane", "Marcelo"]
formations = {"Goalkeeper": players[:2],
"Defender": players[2:]}
set_football_team(name, coach, *players, **formations)
Output
==============================================
Team: Real Madrid
Coach: Zinedine Zidane
Player 1: Keylor Navas
Player 2: K. Casilla
Player 3: Sergio Ramos
Player 4: Varane
Player 5: Marcelo
Goalkeeper: Keylor Navas, K. Casilla
Defender: Sergio Ramos, Varane, Marcelo
但当我跳过传球时
coach
它显示了意外的输出,即使我设置了
教练
到参数中的空字符串:
name = "Real Madrid"
players = ["Keylor Navas", "K. Casilla",
"Sergio Ramos", "Varane", "Marcelo"]
formations = {"Goalkeeper": players[:2],
"Defender": players[2:]}
set_football_team(name, *players, **formations)
Output
==============================================
Team: Real Madrid
Coach: Keylor Navas
Player 1: K. Casilla
Player 2: Sergio Ramos
Player 3: Varane
Player 4: Marcelo
Goalkeeper: Keylor Navas, K. Casilla
Defender: Sergio Ramos, Varane, Marcelo
我知道函数参数的顺序:
positional argument > default argument > variable length non keyword arguments > variable length keyword arguments
上述行为的原因是什么?我错过了什么?
我如何克服这个问题?