Python如何筛选字典中值列表所有元素均存在于指定列表的对应键
问题描述
现有如下Python字典,键为餐品名称,值为制作该餐品需要的食材列表:
meals = {'Pasta Bolognese' : ['pasta', 'tomato sauce', 'ground beef'], 'Cold Salad' : ['greens', 'tomato'], 'Warm Salad' : ['greens', 'tomato', 'corn', 'chickpeas', 'quinoa'], 'Sandwich' : ['bread', 'turkey slices', 'cheese', 'sauce']}
同时给定已有食材列表:
ingredients = ['bread', 'chickpeas', 'tomato', 'greens']
需要筛选出所有需要的食材都包含在已有食材列表中的餐品名称,示例中符合条件的结果为Cold Salad。
实现代码
利用集合的子集判断逻辑即可高效完成筛选,代码如下:
# 先将已有食材转为集合,提升查询效率 ingredient_set = set(ingredients) # 遍历字典筛选符合条件的餐品 matched_meals = [meal for meal, required in meals.items() if set(required).issubset(ingredient_set)]
运行后matched_meals的结果为['Cold Salad'],和示例预期一致。
内容的提问来源于stack exchange,提问作者puppyhead
相关产品推荐
相关产品推荐

