我试图为函数的第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))
以下守则适用—
输出:
您不需要附加到
restaurant
由于您使用的是列表理解,因此可以直接构建列表-
restaurant
,并且只有符合给定条件的键才会添加到列表中。在这里,您不需要编写restaurant.append(key)
,而可以像上面的代码那样,使用restaurant
上的列表理解轻松地直接附加键您可以将其替换为以下列表:
并且不需要将
restaurant
声明为其上方的空列表相关问题 更多 >
编程相关推荐