gpt4 book ai didi

python - 从列表中删除元组

转载 作者:行者123 更新时间:2023-11-28 21:17:54 25 4
gpt4 key购买 nike

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

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])

最佳答案

您不能删除tuple 的成员——您必须删除整个tuple。例如:

x = (1,2,3)
assert x[0] == 1 #yup, works.
x.remove(0) #AttributeError: 'tuple' object has no attribute 'remove'

tuple 是不可变的,这意味着它们无法更改。正如上面的错误所解释的那样,tuple 没有 remove 属性/方法(它们怎么可能?they are immutable)。

相反,尝试从上面的代码示例中删除最后三行并将它们替换为下面的行,这将简单地删除整个 tuple:

studentlist.remove(n)

如果您希望能够更改或删除个人成绩(或更正学生姓名),我建议将学生信息存储在 listdict 中(下面是使用 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)

关于python - 从列表中删除元组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27365728/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com