你好,我是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]})
答案 0 :(得分:1)
您可以将split的结果分配给多个变量:
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