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

Python 尝试在循环时从列表中删除项目,python,python-3.x,nested-lists,Python,Python 3.x,Nested Lists,我对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)

我对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:
    books.remove(x)

确实,您不应该改变正在迭代的列表,但事实并非如此。您在
范围(3)
上循环,并对另一个iterable(
书籍
)进行变异,这不是一个有问题的模式。

您的第一个片段很好。出现此错误的原因是
remove
在列表中不存在要删除的元素时引发异常

尝试:

而不是:

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

确实,您不应该改变正在迭代的列表,但事实并非如此。你在
范围(3)
上循环,并变异另一个可数(
图书
),这不是一个有问题的模式。

检查图书中的
x\u buff
然后
books\u buff。删除(x)
,因为如果找不到项目,则抛出错误,因此你需要进行检查
如果用户评分!=书本中的0和x\u buff:
然后
书本\u buff。删除(x)
执行(1)为什么要洗牌书本?(2) 您正在从“books\u buff”中删除记录,这是一个局部变量。这是一个项目,我正在为另一个任务洗牌。我如何使用books\u buff作为功能副本,因为我已经尝试过了,但是我收到的输出包含了应该删除的元素。检查books\u buff中的
x
然后
books\u buff。删除(x)
因为如果找不到项,则会抛出错误,因此您需要和
if user\u rating!=书本中的0和x\u buff:
然后
书本\u buff。删除(x)
执行(1)为什么要洗牌书本?(2) 您正在从“books\u buff”中删除记录,这是一个局部变量。这是一个项目,我正在为另一个任务洗牌。我如何使用books_buff作为功能副本,因为我已经尝试过了,但是我收到的输出包含了应该删除的元素。