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

问题描述 投票:1回答:1

我对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))
python python-3.x nested-lists
1个回答
0
投票

您的第一段内容很好。您收到此错误的原因是,如果要删除的元素在列表中不存在,则remove会引发异常。

尝试:

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

而不是:

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

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

© www.soinside.com 2019 - 2024. All rights reserved.