我正在用Python制作一个测验编辑器。在用户可以从测验中删除问题的代码部分中,我看到:
ValueError: list.remove(x): x not in list
以下是给出错误的代码:
# Allows the user to remove a question from the quiz
doubleCheck = ""
amountOfQuestions = 0
if choice == "3": # this is where the section of code starts where the user can remove questions
amountOfQuestions = []
print("\nQuestion List")
counter = 1
for count in range(0, len(quiz)): # gets all the questions and prints them
parts = quiz[count].split(",")
amountOfQuestions = amountOfQuestions + 1 # meanwhile this tracks how many questions there are
print("Question ", counter, " :", parts[0])
counter = counter + 1
choice = input(
str("\nChoose question number to remove (type Quit to cancel): ")) # user chooses the question they want to remove
if int(choice) <= amountOfQuestions and int(choice) > 0:
print("Question selected")
doubleCheck = input(
str("Are you sure you want to remove the quesiton? (y/n): ")) # double checks the user wants to remove the question
if doubleCheck == "y":
quiz.remove(choice) # when I choose "y", the error in the question on StackOverflow shows up here
print("Question removed")
quizEditor(quiz) # goes back to the main menu
else:
print("Operation Cancelled")
quizEditor(quiz)
elif choice == "Quit":
print("Operation cancelled - check")
quizEditor(quiz)
else:
print("invalid input")
存储所有问题的“测验”列表的格式如下所示:
["The Question, The correct answer, IncorrectAnswer1, IncorrectAnswer2, IncorrectAnswer3,"]
一个问题及其答案和错误答案存储在列表中的1个元素中,并在需要时通过引用其索引和使用.split()
函数进行拆分
remove()
方法用于从列表中删除匹配的元素。假设您提供了choice
的值作为要删除的索引,那么可以使用pop()
方法您在
quiz.remove(choice)
-行中所做的是调用一个操作,该操作在您的情况下需要精确的字符串匹配这意味着每当
choice
不是列表中的实际元素时,就会失败。你可以用pythonic的方式通过或者通过将var添加到if子句中,确保检查列表中是否存在var:
list.remove()
除了要从列表中删除的值之外,choice
是一个带有数字的字符串,例如'3'
,而不是实际的问题如果要按索引从
quiz
列表中删除,则需要将choice
转换为int
并使用del
或pop
('pop'将在需要时返回已删除的值)相关问题 更多 >
编程相关推荐