我構建了一個程式,其中包含學生的 id 和每個科目的分數串列,其中不同的學生選擇了不同數量的科目。
我試圖在他的標記附近添加主題的名稱,但我找不到任何解決方案。
這是我寫的以下代碼:
def GetStudentDataFromTeacher ():
D ={}
while True:
StudentId = input ("Enter The Student ID:")
StudentMarks = input ("Enter The Student Each Marks:")
MoreStudents = input ('If you dont have more student type "no":')
if StudentId in D:
print (StudentId, "**You Already Type this student")
else:
D[StudentId] = StudentMarks.split (",")
if MoreStudents.lower() == "no":
return D
謝謝!!
uj5u.com熱心網友回復:
您可以要求用戶以特定格式輸入成績,然后將此字串轉換為字典,其中鍵是主題,值是成績。
例如,您可以要求用戶按以下格式輸入:<subject1>--<grade1>,<subject2>--<grade2>.
代碼將是:
def get_students_data():
students_grades = {}
while True:
student_id = input("Enter The Student ID:")
grades = input("Enter the student grades in the following format <subject1>--<grade1>,<subject2>--<grade2>:")
more_students = input('If you dont have more student type "no":')
if student_id in students_grades:
print(student_id, "**You Already Type this student")
else:
students_grades[student_id] = {subject_grade.split("--")[0]: subject_grade.split("--")[1] for subject_grade
in grades.split(",")}
if more_students.lower() == "no":
return students_grades
print(get_students_data())
輸出將是:
# Enter The Student ID: 1
# Enter the student grades in the following format <subject1>--<grade1>,<subject2>--<grade2>:: math--90,history--70
# If you dont have more student type "no": no
{'1': {'math': '90', 'history': '70'}}
可能有更好的方法來實作這種行為(您可以以更加結構化的方式創建一個包含所有成績資料的 json 檔案,然后詢問用戶其路徑并決議它)但是如果您想堅持,上面的代碼段將起作用到您的解決方案。
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/312952.html
上一篇:如何使用條件過濾字典值串列
