Python:统计制作全部食谱所需必备食材的缺失数量
问题描述
给定以下数据:
- 关键食材列表:
list_essentials = ["strawberry", "chocolate", "tomatoe"]
- 现有食材库存字典:
d = {"chocolate":3, "strawberry":1, "beaf":3}
- 食谱字典(每个食谱对应所需食材及数量):
dictionary_recipes = { "cheesecake":{"chocolate":3, "strawberry":4}, "strawberry cake":{"sugar":3, "strawberry":2}, "lasagna":{"beaf":2, "tomatoe":1} }
需要生成一个字典,统计制作所有食谱时,list_essentials中各食材的缺失数量。示例预期输出:
new_dict = {"strawberry": 5, "chocolate": 0, "tomatoe": 1}
计算逻辑:比如草莓现有1个,所有食谱总共需要4+2=6个,缺失量为6-1=5;巧克力现有3个,食谱需要3个,刚好够,缺失0;番茄现有0个,食谱需要1个,缺失1。
用户尝试的代码输出不正确:
for elements in list_essentials: new_dict={} for i, v in d.items(): for a, b in dictionary_recipes.items(): if v = 0: new_dict.append(b) if v > 0: new_dict.append(v-b) print(new_dict)
错误分析
这段代码存在多个问题:
- 循环逻辑混乱:多层嵌套没有聚焦于统计单个食材的总需求,而是无意义遍历所有库存和食谱
- 语法错误:
if v = 0是赋值语句,判断相等应该用==;字典没有append方法,需通过键值对赋值 new_dict每次外层循环都会被重置为空,最终仅保留最后一次循环的结果- 未正确计算食材总需求量,也未处理库存中不存在的食材(比如番茄在
d中无记录,默认库存应为0)
解决方案
以下是实现需求的正确代码:
list_essentials = ["strawberry", "chocolate", "tomatoe"] d = {"chocolate":3, "strawberry":1, "beaf":3} dictionary_recipes = { "cheesecake":{"chocolate":3, "strawberry":4}, "strawberry cake":{"sugar":3, "strawberry":2}, "lasagna":{"beaf":2, "tomatoe":1} } new_dict = {} # 遍历每个关键食材 for ingredient in list_essentials: # 统计该食材在所有食谱中的总需求量 total_needed = 0 for recipe in dictionary_recipes.values(): # 若食谱包含该食材则累加数量,否则加0 total_needed += recipe.get(ingredient, 0) # 获取现有库存,无记录则默认0 stock = d.get(ingredient, 0) # 计算缺失量:总需求减库存,结果为负则取0(表示库存足够) missing = max(total_needed - stock, 0) new_dict[ingredient] = missing print(new_dict)
运行结果:
{'strawberry': 5, 'chocolate': 0, 'tomatoe': 1}
代码说明
- 初始化空字典
new_dict存储最终结果 - 逐个处理关键食材:遍历所有食谱,累加当前食材的总需求量
- 用
get方法安全获取库存,避免因食材不存在报错 - 缺失量取
总需求-库存和0的最大值,确保不会出现负数(库存足够时缺失量为0)
内容的提问来源于stack exchange,提问作者yoopiyo
相关产品推荐
相关产品推荐

