gpt4 book ai didi

python - 嵌套for循环迭代多个字典,有没有更简单的方法?

转载 作者:太空宇宙 更新时间:2023-11-03 15:39:14 24 4
gpt4 key购买 nike

所以我懒惰的屁股正试图在 python 3.x 中创建一个膳食计划生成器,这样我就不必每个星期五都花 30 分钟来弄清楚我应该吃什么,但我是编码新手并且正在努力解决一些问题。我仍在学习 Udemy 类(class),但我想亲自动手编写代码以正确学习。任何人,这是我到目前为止所得到的:

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}

如果能找到一种更简单的方法来计算一天的膳食费用,我将不胜感激。

最佳答案

您可以通过以下方式实现您的设计:

# inside your class:

@staticmethod
def calculate_meal_cost(ingredients, shopdict):
return sum(shopdict[ingredient] for ingredient in ingredients)

@property
def cost(self):
breakfast_cost = self.calculate_meal_cost(breakfasts[self.breakfast], Shop2)
lunch_cost = self.calculate_meal_cost(lunches[self.lunch], Shop2)
dinner_cost = self.calculate_meal_cost(dinners[self.dinner], Shop2)
return breakfast_cost + lunch_cost + dinner_cost

然后:

meal = Meal(...)  # however you pick your meals is fine
meal.cost # note: no parens

关于python - 嵌套for循环迭代多个字典,有没有更简单的方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53565469/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com