如何在循环中分配多个变量

2024-04-26 05:47:10 发布

您现在位置:Python中文网/ 问答频道 /正文

你好,我对python相当陌生,但我正在尝试找出如何分配循环中已经存在的多个变量(在本例中是名称和ID号)

This is the example的循环,因为我正在制作一个程序,手动将人员放入不同的团队,然后打印当前团队

输入应该是名称和ID号。到目前为止,我已经试过了,但不知道该怎么办。也许把它们放到字典里,然后把它们分配给一个团队

team_size = int(input('What is the team size: '))
for i in range(team_size):
    num = num + 1
    print(f'Enter students for team {num}:')
    temp = input().split(' ')
    manual_dict.update({temp[0]: temp[1]})    

Tags: the名称idforinputsizeisexample
1条回答
网友
1楼 · 发布于 2024-04-26 05:47:10

您可以将拆分结果分配给多个变量:

from collections import defaultdict

manual_dict = defaultdict(list)

n_teams = int(input('How many teams you want to enter: '))
for num in range(n_teams):
    team_size = int(input(f'What is the team #{num} size: '))
    for i in range(team_size):
        print(f'Enter #{i} student name and id for team #{num}:')
        name, user_id = input().split(' ')
        user_id = int(user_id)
        manual_dict[num].append({name: user_id})

print(dict(manual_dict))

结果(输出):

How many teams you want to enter: >? 2
What is the team #0 size: >? 1
Enter #0 student name and id for team #0:
>? Jeremy 123
What is the team #1 size: >? 2
Enter #0 student name and id for team #1:
>? Emily 234
Enter #1 student name and id for team #1:
>? Joshua 345

{0: [{'Jeremy': 123}], 1: [{'Emily': 234}, {'Joshua': 345}]}

更多信息here

相关问题 更多 >