簡體   English   中英

從列表中刪除不在元組中的項目

[英]Removing items from the list that are not in the tuple

編寫並測試Python函數leppard以遍歷zoo_list並刪除zoo_dictionary中也沒有的任何項目。 使用以下元組作為字典:

(“獅子”,“老虎”,“熊”,“ chupacabra”,“長頸鹿”,“樹懶”)

n = int(input("Enter the number of animals: "))
zoo_list = []
zoo_dictionary = ( "lion", "tiger", "bear", "chupacabra", "giraffe", "sloth" )
for i in range(n):
    lists = input("Enter the names of each animal: ")
    zoo_list.append(lists)


for i in range(n-1):
    if zoo_list[i] not in zoo_dictionary:
        zoo_list1 = zoo_list.pop(i)

打印(zoo_list)

那是我的代碼,但是當我輸入“ cat”“ dog”“ lion”“ bear”“ monkey”時,我的列表顯示[“ dog”,“ lion”,“ bear”]為什么? 謝謝,麻煩您了 :)

在第二個for循環的第一次迭代中,當i的值為0時,

zoo_list1 = zoo_list.pop(i)

列表中索引為0的元素將被刪除。 現在列表變成

["dog", "lion", "bear", "monkey"]

現在循環繼續進行,在循環的第二次迭代中,i的值為1,在新列表(第一次迭代后形成)中,索引1處的元素為“獅子”。 因此,您缺少元素“狗”。

您所說的字典實際上是一個集合,而不是字典。

如其他答案之一所述,對要迭代的列表進行變異會導致災難。 相反,構建一個新列表,然后將該列表分配給zoo_list

n = int(input("Enter the number of animals: "))
zoo_list = []
zoo_dictionary = ("lion", "tiger", "bear", "chupacabra", "giraffe", "sloth")
for i in range(n):
    zoo_list.append(input("Enter the names of each animal: "))

zoo_list = [animal for animal in zoo_list if animal in zoo_animals]
print(zoo_list)

我已經刪除了不必要的分配給lists變量。 我還刪除了您錯誤的for循環,並將其替換為列表理解。 如果您仍想使用for循環,則可以執行以下操作

temp = []
for animal in zoo_list:
    if animal in zoo_dictionary:
        temp.append(animal)
zoo_list = temp

您還可以使用內置函數filter 用以下內容替換列表理解或for循環(無論使用哪種方法)。

zoo_list = filter(lambda x : x in zoo_animals, zoo_list)

您將獲得相同的結果。

我認為您應該在這里使用while循環。 這是Python 2的代碼。

    n = int(input("Enter the number of animals: "))
    zoo_list = []
    zoo_dictionary = ( "lion", "tiger", "bear", "chupacabra", "giraffe", "sloth" )

    while len(zoo_list) < n:
        item = input("Enter the names of each animal: ")
        zoo_list.append(item)

    print zoo_list, len(zoo_list)
    for i in range(n-1):
        if zoo_list[i] in zoo_dictionary:
            zoo_list.remove(zoo_list[i])

    print zoo_list

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM