Python 从列表中删除元组

Python 从列表中删除元组,python,python-3.x,Python,Python 3.x,我正在编写一个程序,允许用户输入学生记录、查看记录、删除记录和显示平均分数。我很难从列表中删除用户输入的姓名以及学生分数。这是我目前掌握的代码 studentlist=[] a=1 while a!=0: print (""" 1. Add new student records 2. Show all student records 3. Delete a student record 4. Dislay overall average coursework mark 5. Displ

我正在编写一个程序,允许用户输入学生记录、查看记录、删除记录和显示平均分数。我很难从列表中删除用户输入的姓名以及学生分数。这是我目前掌握的代码

studentlist=[]
a=1
while a!=0:
    print ("""
1. Add new student records
2. Show all student records
3. Delete a student record
4. Dislay overall average coursework mark
5. Display overall average exam mark
6. Calculate average marks
0. Exit
Plese select an option
       """)
    a=int(input(""))
    if a==1:
        name=input("Enter a students name: ")
        cmark=int(input("Enter the students coursework mark: "))
        emark=int(input("Enter the students exam mark: "))
        student=(name,cmark,emark)
        print (student)
        studentlist.append(student)
        student=()
    if a==2:
        for n in studentlist:
            print ("Name:", n[0])
            print ("Courswork mark:",n[1])
            print ("Exam mark:", n[2])
            print ("")
    if a==3:
        name=input("Enter a students name: ")
        for n in studentlist:
            if n[0]==name:
                studentlist.remove(n[0])
                studentlist.remove(n[1])
                studentlist.remove(n[2])

不能删除
元组的成员
-必须删除整个
元组
。例如:

x = (1,2,3)
assert x[0] == 1 #yup, works.
x.remove(0) #AttributeError: 'tuple' object has no attribute 'remove'
tuple
s是不可变的,这意味着它们不能更改。如上错误所述,
tuple
s没有remove属性/方法(它们怎么可能?)

相反,请尝试从上面的代码示例中删除最后三行,并用下面的行替换它们,这样只需删除整个
元组即可:

studentlist.remove(n)
如果您希望能够更改或删除单个成绩(或更正学生姓名),我建议将学生信息存储在
列表
dict
中(下面是使用
dict
的示例)


用新列表覆盖旧列表可能更有意义

studentList = [item for item in studentList if item[0] != name]
如果你真的想删除它,你不应该在迭代列表时修改它

for i,student in enumerate(studentList):
    if student[0] == name: 
       studentList.pop(i)
       break #STOP ITERATING NOW THAT WE CHANGED THE LIST

有关使用
dict
而不是
tuple
的示例,请参见我编辑的答案。
for i,student in enumerate(studentList):
    if student[0] == name: 
       studentList.pop(i)
       break #STOP ITERATING NOW THAT WE CHANGED THE LIST