簡體   English   中英

如何檢查列表中的項目是否在另一個列表中?

[英]How do I check if an item from a list is in another list?

我試圖編寫一個簡單的 Python 3 程序但找不到答案。

fruits = ["strawberries", "apples", "bananas", "pomegranates", "blueberries", "dragon fruits", "papayas", "pears", "oranges", "mango", "tomatoes", "peaches", "melons", "watermelons"]
favoritefruits = [fruits[0], fruits[2], fruits[3], fruits[7], fruits[8], fruits[13]]

for i in fruits:
    if fruits[i] in favoritefruits:
        print("I'm gonna buy some " + fruits[i] + " because they are one of my favorite fruits.")
    else:
        print("I'm not going to buy " + fruits[i] + ", I don't like them.")

正如@wkl 所說, for i in fruits將遍歷所有水果名稱,而不是索引。 fruits[i]替換為i (盡管名稱更具描述性更好)將解決此問題:

fruits = ["strawberries", "apples", "bananas", "pomegranates", "blueberries", "dragon fruits", "papayas", "pears", "oranges", "mango", "tomatoes", "peaches", "melons", "watermelons"]
favoritefruits = [fruits[0], fruits[2], fruits[3], fruits[7], fruits[8], fruits[13]]

for fruit in fruits:
    if fruit in favoritefruits:
        print("I'm gonna buy some " + fruit + " because they are one of my favorite fruits.")
    else:
        print("I'm not going to buy " + fruit + ", I don't like them.")

你有兩個列表

fruits = ["strawberries", "apples", "bananas", "pomegranates", "blueberries", "dragon fruits", "papayas", "pears", "oranges", "mango", "tomatoes", "peaches", "melons", "watermelons"]

favoritefruits = [fruits[0], fruits[2], fruits[3], fruits[7], fruits[8], fruits[13]]

要迭代,您不需要使用i 只需使用

for fruit in fruits:
    if fruit in favoritefruits:
        print("I'm gonna buy some " + fruit + " because they are one of my favorite fruits.")
    else:
        print("I'm not going to buy " + fruit + ", I don't like them.")

Output:

I'm gonna buy some strawberries because they are one of my favorite fruits.
I'm not going to buy apples, I don't like them.
I'm gonna buy some bananas because they are one of my favorite fruits.
I'm gonna buy some pomegranates because they are one of my favorite fruits.
I'm not going to buy blueberries, I don't like them.
I'm not going to buy dragon fruits, I don't like them.
I'm not going to buy papayas, I don't like them.
I'm gonna buy some pears because they are one of my favorite fruits.
I'm gonna buy some oranges because they are one of my favorite fruits.
I'm not going to buy mango, I don't like them.
I'm not going to buy tomatoes, I don't like them.
I'm not going to buy peaches, I don't like them.
I'm not going to buy melons, I don't like them.
I'm gonna buy some watermelons because they are one of my favorite fruits.

for i in fruits將返回水果本身而不是索引,所以當你做fruits[i] python 需要一個 int 但你給了它一個字符串。 您可以for i in range(len(fruits))以便fruits[i]返回水果,但在您的代碼中,您只使用索引來獲取水果,因此更清潔的解決方案是將for i in fruits重寫為for fruit in fruits ,只需在循環內使用fruit

我認為這種方法可能有用:

首先,如果你得到一個水果,並且列表發生了變化,那么favorite_fruits現在的偏移量至少為 1。要解決這個問題,你可以這樣做:

def get_favourites(favourites):
    """ Get favourite fruits from a list """
    new_favourite_fruits = []
    
        for fruit in favourites:
            try:
                new_favourite_fruits.append(fruits.index(fruit))
            except IndexError:
                print("Couldn\'t find an {fruit} in the list of fruits :( ")
    return new_favourite_fruits 

因此,如果您要將其應用於原始代碼:

fruits = ["strawberries", "apples", "bananas", "pomegranates", "blueberries", "dragon fruits", "papayas", "pears", "oranges", "mango", "tomatoes", "peaches", "melons", "watermelons"]
favourite_fruits = get_favourites(['apples','mango','melons'])

for fruit in new_favourite_fruits(['apples','oranges','peaches']):
    print(f"I\'m going out to buy a {fruit}")

此外,根據您使用列表的程度,您可能會發現這很有用:

for item, fruit in enumerate(fruits):
    print(f"I am going to buy a {fruit} at {item}")

enumerate的優點是它允許您同時獲取索引和水果。

暫無
暫無

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

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