【问题标题】:Convert two loops to a list comprehension将两个循环转换为列表推导
【发布时间】:2020-12-18 10:40:17
【问题描述】:

我正在尝试为函数的第 3-6 行编写一个列表推导。它根据guests_diet 中的选择返回相关餐厅。结果应该是字符串“对不起,没有餐厅符合您的限制”。该功能有效,但我面临着做列表理解的挑战。我想出了下面的代码,但结果不正确。有人可以帮忙吗?

尝试生成错误结果的代码 -

ans = [restaurant.append(key) for key, value in rest_names.items()\
                  for x in range(len(cuisine)) if cuisine[x] in value]

代码 -

def no_you_pick(rest_names, cuisine):
    restaurant = []
    for key, value in rest_names.items():
        for x in range(len(cuisine)):
            if cuisine[x] in value:
                restaurant.append(key)
    restaurant.sort()
    if len(restaurant) == 0:
        return "Sorry, no restaurants meet your restrictions"
    elif len(restaurant) == 1:
        return ' '.join(restaurant)
    return ', '.join(restaurant)

grading_scale = {"blossom": ["vegetarian", "vegan", "kosher", "gluten-free", "dairy-free"], \
             "jacob's pickles": ["vegetarian", "gluten-free"], \
             "sweetgreen": ["vegetarian", "vegan", "gluten-free", "kosher"]}
guests_diet = ["buttered-lobster"]
print(no_you_pick(grading_scale, guests_diet))

【问题讨论】:

    标签: python list-comprehension


    【解决方案1】:

    以下代码将起作用 -

    def no_you_pick(rest_names, cuisine):
        restaurant = [key for key,value in rest_names.items() for x in range(len(cuisine)) if cuisine[x] in value]
        restaurant.sort()
        if len(restaurant) == 0:
            return "Sorry, no restaurants meet your restrictions"
        elif len(restaurant) == 1:
            return ' '.join(restaurant)
        return ', '.join(restaurant)
    
    grading_scale = {"blossom": ["vegetarian", "vegan", "kosher", "gluten-free", "dairy-free"], \
                 "jacob's pickles": ["vegetarian", "gluten-free"], \
                 "sweetgreen": ["vegetarian", "vegan", "gluten-free", "kosher"]}
    guests_diet = ["buttered-lobster"]
    print(no_you_pick(grading_scale, guests_diet))
    print(no_you_pick(grading_scale, ['vegan']))
    

    输出:

    Sorry, no restaurants meet your restrictions
    blossom, sweetgreen
    

    您不需要附加到restaurant

    ans = [restaurant.append(key) for key, value in rest_names.items() for x in range(len(cuisine)) if cuisine[x] in value]
    

    由于您使用的是列表推导,您可以直接构建您的列表 - restaurant,并且只有与给定条件匹配的键才会添加到列表中。在这里,您可以使用restaurant 上的列表推导轻松地直接附加键,而不是编写restaurant.append(key),就像上面的代码中所做的那样

    【讨论】:

      【解决方案2】:

      您可以将其替换为以下列表理解:

      restaurant = [key for key, value in rest_names.items()\
                    if any(item in cuisine for item in value)]
      

      并且无需将restaurant 声明为其上方的空列表。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-12-13
        相关资源
        最近更新 更多