所以我在 Stack Overflow 用戶的幫助下制作了這個功能,這里是..
def totalcal(data):
calorie_dict = {}
for el in data:
food, values = el.split(':')
a, b, c = values.split(',')
calories = (int(a) * 5) (int(b) * 5) (int(c) * 9)
calorie_dict[food] = calories
return calorie_dict
def rdict(recipes):
recipes_splitted = {}
for r in recipes:
recipe_name, parts = r.split(":")
recipe_parts = {}
for part in parts.split(','):
product, number = part.split('*')
recipe_parts[product] = int(number)
recipes_splitted[recipe_name] = recipe_parts
return recipes_splitted
def recipecal(recipes, data):
for recipe_name in rdict(recipes):
recipe_parts = rdict(recipes)[recipe_name]
calories = 0
for product in recipe_parts:
number = recipe_parts[product]
calories = number * totalcal(data)[product]
return calories
print(recipecal(["Pork Stew:Cabbage*5,Carrot*1,Fatty Pork*10",
"Green Salad1:Cabbage*10,Carrot*2,Pineapple*5",
"T-Bone:Carrot*2,Steak Meat*1"]
,["Cabbage:4,2,0", "Carrot:9,1,5", "Fatty Pork:431,1,5",
"Pineapple:7,1,0", "Steak Meat:5,20,10", "Rabbit Meat:7,2,20"]))
但是,此功能有效,因為recipecal(recipes, data)僅列印出串列中第一個輸入的解決方案,就像輸出僅此...
22295
這是結果,["Pork Stew:Cabbage*5,Carrot*1,Fatty Pork*10",但我的代碼忽略了串列中的其余輸入.. 我應該在這里更改什么才能使其作業?
uj5u.com熱心網友回復:
的執行return calories太早了,因為它在回圈內,因此也完成了回圈,這就是其他條目沒有被處理的原因。
對此的解決方案是將其放置在內回圈之外。在這種情況下,回傳的卡路里只會列印最后一個條目,這不是您想要的。
因此,最終的解決方案是創建一個串列,該串列將存盤每個食譜的卡路里并回傳該串列。
編輯應該是這樣的
def recipecal(recipes, data):
calories_list = []
for recipe_name in rdict(recipes):
recipe_parts = rdict(recipes)[recipe_name]
calories = 0
for product in recipe_parts:
number = recipe_parts[product]
calories = number * totalcal(data)[product]
calories_list.append(calories)
return calories_list
輸出
[22295, 690, 405]
如果你想要所有卡路里的總和,那么只需使用 sum(list)
uj5u.com熱心網友回復:
您在for recipe_name in rdict(recipes):回圈中有一個 return 陳述句,因此它將在回圈之前回傳并且永遠不會到達其他元素。通過移動calories = 0并return calories退出回圈來修復它。
def recipecal(recipes, data):
calories = 0
for recipe_name in rdict(recipes):
recipe_parts = rdict(recipes)[recipe_name]
for product in recipe_parts:
number = recipe_parts[product]
calories = number * totalcal(data)[product]
return calories
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/363154.html
上一篇:如何計算字典理解中單詞的出現次數
