繁体   English   中英

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

[英]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

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

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 ),这不是一个有问题的模式。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM