尝试在循环时从列表中删除项目

Attempting to remove items from a list while looping

我是 python 的新手,我一直在尝试从这段代码中删除评分不为零的图书:

def ratings():
    for i in range(3):
        x = shuffle[i]
        print(x)
        user_rating = int(input(""))
        new_ratings.append(user_rating)
        if user_rating != 0:
            books.remove(x)
        global smalldict 
        smalldict = dict(zip(shuffle,new_ratings))

    print("new user's rating: " + str(smalldict))

但是当我 运行 代码两次时,我不断收到此错误:

list.remove(x): x not in list

现在,在做了一些研究之后,我发现我不应该从我正在循环的列表中删除项目,一个解决方案是创建一个副本,但是,当我 运行 函数使用副本,不会删除任何元素。这是我尝试过的示例:

def ratings():
    for i in range(3):
        books_buff = books[:]
        x = shuffle[i]
        print(x)
        user_rating = int(input(""))

        new_ratings.append(user_rating)
        if user_rating != 0:
            books_buff.remove(x)
        global smalldict 
        smalldict = dict(zip(shuffle,new_ratings))

    print("new user's rating: " + str(smalldict))

你的第一个片段很好。您收到此错误的原因是,如果列表中不存在您尝试删除的元素,remove 会抛出异常。

尝试:

if user_rating != 0 and x in books_buff:
    books.remove(x)

而不是:

if user_rating != 0:
    books.remove(x)

的确,您不应该改变正在迭代的列表,但事实并非如此。您正在遍历 range(3) 并改变另一个可迭代对象 (books),这不是一个有问题的模式。