仅当新条目大于前一个条目时才更新字典

问题描述 投票:0回答:1

我需要创建一个学生数据库,其中课程(以元组的格式(课程名称:int,年级:int)添加到字典(学生:dict)中。但是,如果学生已经完成了课程(有已经是数据库中同名的课程),如果新成绩大于旧成绩,这应该只替换以前的值。

我已经尝试了几件事,但正在努力确保只有更高的成绩才会更新字典

def add_course(students: dict,   name_student: str, course_info: tuple[str, float]):
    course_name = course_info[0]
    grade = course_info[1]
    courses = students[name_student ]

    if name_student in students.keys(): 
        if courses == "no completed courses": #check whether has any entry
            students[name_student] = [course_info]
            return
        else: #= student is in database and has other entries 
            for i in range(len(courses)):
                if courses[i][0] == course_name: #if there is course name with other 
                    if int(courses[i][1]) < int(grade):
                        courses[i][1] = grade
                        students[name_student] = courses
                        break
                    else: #if grade is smaller, do nothing 
                        break
             #if no course with same name
                elif course_name not in courses[i][0]:
                    print("courses", courses)
                    print("course name", course_name)
                    courses.append((course_name, grade))
                    students[name_student] = courses
                  print("students[name_student]",students[name_student])
                    return
    else:
        return "Student not in the database"


    #output
    # print(f"{name_student}:")

if __name__ == "__main__":
    students = {"Peter": "no completed courses"}
    add_course(students, "Peter", ("Introduction to 
Programming", 5))
    add_course(students, "Peter", ("Advanced Programming", 7))
    add_course(students, "Peter", ("Advanced Programming", 5))
    print_student(students, "Peter")
python dictionary
1个回答
0
投票

您的数据结构使逻辑比需要的更加复杂。理想情况下,学生的课程和成绩列表应该是一本以课程名称为键的字典。此外,缺少已完成的课程应该用空列表或字典而不是字符串来表示(这会使内容类型不规则,并且在逻辑中需要附加条件)。

在不改变数据结构的情况下,该函数可以临时将课程列表转换为字典,更新成绩并将其转回学生列表:

def add_course(students: dict,   name_student: str, course_info: tuple[str, float]):
    if name_student not in students:
        return "Student not in the database"
    course,grade   = course_info
    courses        = students[name_student]
    grades         = dict( [] if courses == "no completed courses" else courses)
    grades[course] = max(grades.get(course,newGrade),newGrade)
    students[name_student] =  list(grades.items())

如果有更合适的数据结构(即学生的值是{course:grade}字典,没有课程完成时为空),功能会更简单:

def add_course(students: dict,   name_student: str, course_info: tuple[str, float]):
    if name_student not in students:
        return "Student not in the database"
    course,grade    = course_info
    courses         = students[name_student]
    courses[course] = max(courses.get(course,newGrade),newGrade)
© www.soinside.com 2019 - 2024. All rights reserved.