有没有办法可以在收集分数之前收集所有名称和ID?

时间:2018-11-26 17:17:03

标签: python dictionary

有没有一种方法可以在获取每个作业的成绩之前收集所有学生的姓名和ID?目前,我的代码一次遇到一位学生,但是有没有办法一次召回他们的ID,然后再增加他们的成绩?

nameID = {}

while input("Would you like to add a student? ") == "yes":
    name = input("What is the student's name?: ")
    ID = input("What is the student's ID?: ")
    nameID[ID] = name   
    scores = []
    assignments = int(input("How many assignments were given? "))

    for i in range(assignments): 
        score = int(input("Enter {}'s score for assignment {} (0-100): ".format(nameID[ID], i+1)))
        scores.append(score)

    average = (sum(scores))/assignments
    print("{}'s average score was {:.1f}".format(name, average))
    nameID[ID] = {"Name": name, "Scores": scores}

print(nameID)

1 个答案:

答案 0 :(得分:2)

首先,您需要完成有关Python数据类型以及如何应用它们的某种教程。看来您正在尝试建立一个学生数据表,包括姓名,ID和每个学生的分数列表。

这建议一个数据框架-尽管该数据结构可能超出了您在课堂上学到的内容。同时,您似乎正在尝试使用dict来完成这项工作-这是合理的。但是,您尚未以Python能够识别的方式设计结构。

我不知道您是否需要按学生姓名或学生ID访问数据;您发布的代码对关系感到困惑。假设您想按名称进行操作,也许您需要一个嵌套的dict:上层名称,下面的ID和分数。

ledger = {}
while input("Would you like to add a student? ") == "yes": 
    name = input("What is the student's name?: ")
    id = input("What is the student's ID?: ")
    ledger[name] = {"ID": id}

assignments = int(input("How many assignments were given? "))

for name in ledger: 
    score_list = []
    for i in range(assignments):
        score = input("Enter {}'s score for assignment {}: ".format(name, i+1))
        score_list.append(int(score))

    ledger[name]["scores"] = {"ID": ID, "scores": scores}

这是否使您在总体解决方案上有些偏离?