【发布时间】:2021-05-22 23:16:45
【问题描述】:
我有两本字典,我正在尝试使用 For 循环与 If 条件混合来实现以下目标。
- 对于 meal_recipe 中的每个“项目”,检查项目是否在储藏室中。
- 如果是,请检查meal_recipe 的“价值”是否大于食品储藏室。如果是,则在 shopping_list 中添加键 + 差值。
- 如果没有,请将 meal_recipe 的 Key 和 value 都添加到 shopping_list 中。
meal_recipe = {'pasta': 2, 'garlic': 2, 'sauce': 3,
'basil': 4, 'salt': 1, 'pepper': 2,
'olive oil': 2, 'onions': 2, 'mushrooms': 6}
pantry = {'pasta': 3, 'garlic': 4,'sauce': 2,
'basil': 2, 'salt': 3, 'olive oil': 3,
'rice': 3, 'bread': 3, 'peanut butter': 1,
'flour': 1, 'eggs': 1, 'onions': 1, 'mushrooms': 3,
'broccoli': 2, 'butter': 2,'pickles': 6, 'milk': 2,
'chia seeds': 5}
我是 python 中的菜鸟,所以到目前为止我一直停留在下面的代码中,不知道如何继续:
for item, stock in meal_recipe.items():
if item in pantry:
if mean_recipe [stock] > pantry [stock]: ????? Not sure
Shopping_list={item for item in mean_recipe} ????? Not sure
谁能告诉我应该怎么做?
【问题讨论】:
-
第一步:让缩进正确。 Python 需要这个。
-
meal_recipe和pantry是什么?不应该是Dict1和Dict2吗? -
指令说“对于 dict2 中的每个项目”。你为什么要循环
Dict1.items()?不应该是Dict2.items()吗? -
如果你使用变量
meal_recipe、pantry和shopping_list而不是像Dict1和Dict2这样无意义的名字,实际上会更容易理解。 -
"如果没有,请将 meal_recipe 的 Key 和 value 添加到 shopping_list。"好吧,如果你想添加一些东西到
shopping_list,它应该首先存在,对吧?然后,想想添加它所涉及的内容。
标签: python pandas loops dictionary