所以我懒惰的后部正在尝试在 python 3.x 中创建一个膳食计划生成器,这样我就不必每周五花 30 分钟来弄清楚我应该吃什么,但我是编码新手,并且在一些事情上苦苦挣扎。我仍在学习 Udemy 课程,但我想让我的手指弄脏代码以正确学习。任何人,这是我到目前为止所得到的:
class Meals():
def __init__(self,breakfast,lunch,dinner):
self.breakfast=breakfast
self.lunch=lunch
self.dinner=dinner
def __str__(self):
return f"Breakfast will be {self.breakfast}.\nLunch will be {self.lunch}.\nDinner will be {self.dinner}."
def cost(self):
day_meals=[self.breakfast,self.lunch,self.dinner]
day_cost=0
for i in day_meals:
for ingredient in i:
for key,value in Shop2.items():
if key in ingredient:
day_cost+=value
return f"Today will cost £{round(day_cost,2)}."
如果我做:
monday_meals=Meals(random.choice(list(breakfasts.keys())),random.choice(list(lunches.keys())),random.choice(list(dinners.keys())))
然后调用 monday_meals.breakfast,然后我得到我想要的结果,即从“早餐”字典中随机选择的键,但每当我调用:monday_meals.cost() 时,我会得到 0 英镑,并且没有错误显示。
作为参考,我的测试词典如下:
breakfasts={"a bowl of Rice Crispies":["cereal_1","milk"],"Weetabix":["cereal_2","milk"],"some Golden Grahams":["cereal_3","milk"],"toast":["bread","butter"],"scrambled eggs":["egg","egg","milk"]}
lunches={"cereal bars":["cereal_bar","cereal_bar"],"a boring ham sandwich":["bread","ham"],"some fruit":["banana","apple"],"salad":"salad_bag"}
dinners={"Student Meal #1":["mince","red_sauce","pepper","onion"],"Student Meal #2":["c_breast","white_sauce","onion","pepper"],"Student Meal #3":["egg","pepper","tomato","onion"]}
Shop2={"egg":0.3,"tomato":0.35,"pepper":0.33,"onion":0.4,"mince":1.2,"c_breast":0.7,"rice":0.8,"red_sauce":1.4,"white_sauce":1.5,"cereal_1":0.4,"milk":0.13,"cereal_2":0.35,"cereal_3":0.45,"bread":0.04,"butter":0.04,"cereal_bar":0.75,"ham":0.25,"banana":0.3,"apple":0.3,"salad":0.75}
我真的很感激任何帮助找到一种更简单的方法来计算一天的膳食成本。