这个Python列表代码有什么问题?

时间:2017-09-20 01:29:27

标签: python list

我对此代码有疑问:

menu = ""
student = []
print ("What would you like to do?")
print ("\t[1] Show full gradebook")
print ("\t[2] Add Student")
print ("\t[3] Remove Student")
print ("\t[4] Modify Student Information")
print ("\t[5] Display Highest Grade")
print ("\t[6] Display Lowest Grade")
print ("\t[7] Quit")

# loop until the user decides to quit
while menu != 7:
    menu = int(input("Enter selection [1-7]"))
    if menu == 1:
        print("Name\tGrade")
        # loop through all students
        for s in student:
            print(s[0]+"\t"+str(s[1]))    
    elif menu == 2:
        # prompt user for student name
        sname = input("Student Name?") 
        # prompt user for student grade
        sgrade = int(input("Student Grade?"))
        # append student information to list
        student.append([sname, sgrade])    
    elif menu == 3:
        sname = input("Student to remove?")
        try:
            student.remove([sname, sgrade])
        except:
            if sname not in student:
                print("Not in table.")
    elif menu == 4:
        sname = input("Student to modify?")
        for s in student:
            print(s[0]+"\t"+str(s[1]))
        try:
            student.remove([sname, sgrade])
            sname = input("Name: (press Enter to keep original value)")
            sgrade = int(input("Grade: (press Enter to keep original value)"))
            student.append([sname, sgrade])
        except:
            if sname not in student:
                print("Not in table.")
    elif menu == 5:
        try:
            print(sname + " had the highest score in the class: " + str(sgrade))
        except:
            pass
    elif menu == 6:
        try:
            print(sname + " had the lowest score in the class: " + str(sgrade))
        except:
            pass
    elif menu >= 8:
        print("Invalid selection.")

print ("Terminating program... Goodbye!")

每次我尝试三到六个选项与多个学生一起时,它会为列表底部的学生做。此外,我想知道在修改学生信息时如何保留某个学生的原始姓名或成绩。

1 个答案:

答案 0 :(得分:1)

在每次操作之前,代码不会从列表中检索学生详细信息。而是使用先前的sgrade值,sgrade将始终是列表中最后一个学生使用的值。因此,选项3-6仅适用于最后一个学生。

您可以在搜索列表时仅使用学生姓名来修复它。例如,要删除学生(选项3),您可以使用列表理解:

student = [s for s in student if s[0] != sname]
你的代码中的

elif menu == 3:
    sname = input("Student to remove?")
    len_orig = len(student)
    student = [s for s in student if s[0] != sname]
    if len_orig == len(student):
        # length unchanged therefore student not in list
        print("Not in table.")

选项4是上述的变体。要找到成绩最高的学生,您可以使用max()功能:

highest = max(student, key=lambda x: x[1])

同样,min()可以找到最低价:

lowest = min(student, key=lambda x: x[1])

就数据结构而言,字典是比列表更好的选择。使用学生姓名作为密钥,将成绩作为值。然后添加,删除或修改学生等操作是微不足道的:

students = {}    # initialise

# add a student
sname = input("Student Name?") 
sgrade = int(input("Student Grade?"))
students[sname] = sgrade

# remove student
sname = input("Student to remove?")
if sname in students:
    del students[sname]
else:
    print("Not in table.")