簡體   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