【问题标题】:How do I check if an item from a list is in another list?如何检查列表中的项目是否在另一个列表中?
【发布时间】:2022-08-24 12:24:47
【问题描述】:

我试图编写一个简单的 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.\")
  • i 是水果本身,所以fruits[i] 会引发异常(使用str 作为索引或类似的东西)。你只想要if i in favoritefruits
  • 也可以使用字符串插值print(f\"I\'m not gonna buy some {fruit}, I don\'t like \'em.\") :)

标签: python list


【解决方案1】:

正如@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.")

【讨论】:

    【解决方案2】:

    您有两个列表:fruits 和 favoritefruits

    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.")
    

    输出:

    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.
    

    【讨论】:

      【解决方案3】:

      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循环。

      【讨论】:

        【解决方案4】:

        我认为这种方法可能有用:

        首先,如果你得到一个水果,并且列表发生了变化,那么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 的优点是它允许您同时获得索引和水果。

        【讨论】:

        • 这不能回答问题。
        猜你喜欢
        • 1970-01-01
        • 2013-12-12
        • 2019-07-26
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-03-02
        • 1970-01-01
        相关资源
        最近更新 更多