我正在编写一个程序,允许用户输入学生记录,查看记录,删除记录和显示标记的平均值。我无法从列表中删除用户输入的名称以及学生标记。这是我到目前为止的代码
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])
答案 0 :(得分:4)
您无法删除tuple
的成员 - 您必须删除整个tuple
。例如:
x = (1,2,3)
assert x[0] == 1 #yup, works.
x.remove(0) #AttributeError: 'tuple' object has no attribute 'remove'
tuple
是不可变的,这意味着它们无法更改。正如上面的错误所解释的那样,tuple
没有删除属性/方法(他们怎么可能?they are immutable)。
相反,请尝试从上面的代码示例中删除最后三行,并将其替换为下面的行,这将只删除整个tuple
:
studentlist.remove(n)
如果您希望能够更改或删除个别成绩(或更正学生的姓名),建议您将学生信息存储在list
或dict
中(例如使用dict
如下所示。
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:
promptdict1 = {'name': 'Enter a students name: ', \
'cmark': 'Enter the students coursework mark: ', \
'emark': 'Enter the students exam mark: '}
studentlist.append({'name': input(promptdict1['name']), \
'cmark': int(input(promptdict1['cmark'])), \
'emark': int(input(promptdict1['emark']))})
print(studentlist[-1])
if a==2:
promptdict2 = {'name': 'Name:', \
'cmark': 'Courswork mark:', \
'emark': 'Exam mark:'}
for student in studentlist:
print(promptdict2['name'], student['name'])
print(promptdict2['cmark'], student['cmark'])
print(promptdict2['emark'], student['emark'], '\n')
if a==3:
name=input("Enter a students name: ")
for n in studentlist:
if n['name']==name:
studentlist.remove(n)
答案 1 :(得分:2)
用新列表覆盖旧列表可能更有意义
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