问题描述
我正在尝试为该函数的第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","kosher"]}
guests_diet = ["buttered-lobster"]
print(no_you_pick(grading_scale,guests_diet))
解决方法
以下代码将起作用-
<ul className="tagcloud">
{tags.group.map((tag,idx) => {
var index = tag.edges[0].node.frontmatter.tags.indexOf(
tag.fieldValue
)
return (
<li key={idx}>
<Link
to={`/tags/${tag.edges[0].node.fields.tags[index]}`}
className="transition link"
>
{tag.fieldValue}
</Link>
</li>
)
})}
</ul>
输出:
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","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.append(key)
上使用列表推导轻松地直接附加键
您可以将其替换为以下列表理解:
this.loadingController.create({
message: 'Loading,please wait...'
}).then((loading) => {
loading.present();
Promise.all([apiCallOne(),apiCallTwo(),apiCallThree()])
.catch((err) => {
console.log(err);
loading.dismiss();
})
.then((results) => {
// do something with results ...
loading.dismiss();
});
});
无需声明restaurant = [key for key,value in rest_names.items()\
if any(item in cuisine for item in value)]
是其上方的空白列表。