You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

将Python函数双循环改写为列表推导式遇错求协助

修正餐厅筛选函数的列表推导式错误

嘿,我来帮你搞定这个列表推导式的问题!首先先理清楚你原代码的逻辑:遍历每个餐厅,只要餐厅支持客人要求的任意一种饮食限制,就把餐厅名加入列表,最后根据列表长度返回对应结果。

先看你原有的可正常运行的代码:

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

你尝试的错误推导式是:

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

问题出在哪?

你的核心错误有两个:

  1. append()的返回值是None:列表推导式会把每一次迭代的结果收集起来,而restaurant.append(key)执行后返回的是None,所以最后你的ans列表里全是None,完全不是你想要的餐厅名称列表。
  2. 冗余的索引遍历:原代码里用range(len(cuisine))再取cuisine[x]没必要,直接遍历cuisine里的每个饮食项更简洁。

修正后的正确写法

直接用列表推导式生成符合条件的餐厅名称列表,不需要提前创建空列表再append:

def no_you_pick(rest_names, cuisine):
    # 列表推导式直接生成符合条件的餐厅名列表
    restaurant = [key for key, value in rest_names.items()
                  for diet in cuisine
                  if diet 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)

测试验证

用你给的测试案例guests_diet = ["buttered-lobster"]运行,函数会正确返回"Sorry, no restaurants meet your restrictions";如果换成guests_diet = ["vegetarian"],会返回排序后的blossom, jacob's pickles, sweetgreen,和原函数的输出完全一致。

内容的提问来源于stack exchange,提问作者LennyC

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.08 23:47:35