ValueError:list.remove(x):尝试从列表中删除元素时x不在列表中

2024-09-30 16:41:40 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在用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()函数进行拆分


Tags: thetoinifcounterquizremovequestions
3条回答

remove()方法用于从列表中删除匹配的元素。假设您提供了choice的值作为要删除的索引,那么可以使用pop()方法

quiz.pop(choice)

您在quiz.remove(choice)-行中所做的是调用一个操作,该操作在您的情况下需要精确的字符串匹配

这意味着每当choice不是列表中的实际元素时,就会失败。你可以用pythonic的方式通过

try:
    quiz.remove(choice)
except ValueError:
    # do whatever

或者通过将var添加到if子句中,确保检查列表中是否存在var:

if choice in quiz:
     #...

list.remove()除了要从列表中删除的值之外,choice是一个带有数字的字符串,例如'3',而不是实际的问题

如果要按索引从quiz列表中删除,则需要将choice转换为int并使用delpop('pop'将在需要时返回已删除的值)

index = int(choice)
del quiz[index]
# or
quiz.pop(index)

相关问题 更多 >