我正在编写一个程序,该程序向用户询问2到10之间的许多团队,然后以该团队中的团队名称和球员名称为止,直到用户进入。然后,它进入下一个团队的名字和球员。最后,一旦进入最终团队,它就会打印每个团队的名称和每个团队中的球员名称。问题是我不知道如何在循环继续前进时存储团队的名称和球员的名称。



numteams = int(input("How many teams are there? "))
if numteams < 2 or numteams > 10:
    print("Please enter between 2 and 10 teams.")
#Ensures the proper number of teams are entered.
else:
    print("Please enter a team name when prompted. Then enter player names for that team. \nWhen done entering player names for that team, type done.")
    z = 1
    while z <= numteams:
    #overall loop to inquire about all teams
        teamname = input("Please enter the name of Team #" + str(z) + ": ")
        name = " "
        while name != "done":
        #loop to ask for names of players 
            name = input("Please enter the name of a player for team " + teamname + ": ")
        z = z + 1
    

这是我当前的代码,它根据有多少球队的数量,成功地询问了团队的名称和球员的名称循环的迭代。 for-loop会更有效吗?我试图为每个团队创建一个列表,但是该程序再次循环后也会被覆盖。

我的目标输出将显示为

团队1:钢人队

球员#1:鲍勃

球员2:乔

团队2:海豚

球员#1:蒂米

玩家#2:Eli

等等

分析解答

仅对原始代码进行最小数量的更改,我们可以将字典添加到存储团队名称为键和播放器名称(IT值)中的播放器名称。

team_dict = {}

numteams = int(input("How many teams are there? "))
if numteams < 2 or numteams > 10:
    print("Please enter between 2 and 10 teams.")
    
#Ensures the proper number of teams are entered.
else:
    print("Please enter a team name when prompted. Then enter player names for that team. \nWhen done entering player names for that team, type done.")
    z = 1
    
    while z <= numteams:
        
        #overall loop to inquire about all teams
        teamname = input("Please enter the name of Team #" + str(z) + ": ")
        
        player_names = []
        player_name = ""
        
        #loop to ask for names of players
        while player_name != "done":
            
            player_name = input("Please enter the name of a player for team " + teamname + ": ")
            player_names.append(player_name)
            
        team_dict[teamname] = player_names
        
        z = z + 1

如上所述,这生成具有以下数据结构的字典

print(team_dict)

{'Yankees': ['Me', 'Myself', 'I', 'done'],
 'Pirates': ['Me again', 'Myself again', 'I again', 'done']}

然后,我们可以迭代团队,然后为每个条目播放名称,并控制我们打印输出的方式。例如

for key,val in team_dict.items():
    
    print(f"Team: {key}")
    
    for player in val:
        print(f"    Player: {player}")


# Team: Yankees
#     Player: Me
#     Player: Myself
#     Player: I
#     Player: done
# Team: Pirates
#     Player: Me again
#     Player: Myself again
#     Player: I again
#     Player: done