【发布时间】:2021-02-11 06:22:30
【问题描述】:
我有一个脚本可以计算食谱的营养信息。用户输入成分的名称,成分的克数比例,并提供一个 .txt 文件,其中存储了每种成分的营养信息(每 100g),这实际上是一个字典,其键是成分和不同的值(kcal、kj、fat 等)是每个键内的列表。 例如,假设成分是茄子、橄榄油和柠檬汁。
到目前为止,该脚本将包含以下信息:
nutrition_dict = {'kcal': 0, 'kj': 0, 'fat': 0, 'saturated fat': 0, 'carbohydrates': 0, 'sugar': 0, 'protein': 0, 'salt': 0}
nutrition_file = {'eggplant':[24, 100, 0.2, 0, 5.7, 2.4, 1, 0.005], 'olive oil':[884, 3701, 100, 13.8, 0, 0, 0, 0.005], 'lemon juice':[25, 105, 0, 0, 8.6, 2.4, 0.4, 0.0025]}
amount_of_ingredients = {'eggplant': 300, 'olive oil': 20, 'lemon juice': 5}
total_desired_recipe = 325
现在我需要做的是:
- 计算总配方(本例中为 325g)的总 kcal、kj、脂肪等
- 计算每100g配方的总kcal、kj、脂肪等。
我的脚本可以工作,但它很丑陋,改进它会让我学习更好的方法来获得预期的结果。
for key in nutrition_file:
i = 0
for i in range(8):
if i == 0:
nutrition_dict['kcal'] = nutrition_dict['kcal'] + nutrition_file[key][i]
elif i == 1:
nutrition_dict['kj'] = nutrition_dict['kj'] + nutrition_file[key][i]
elif i == 2:
nutrition_dict['fat'] = nutrition_dict['fat'] + nutrition_file[key][i]
elif i == 3:
nutrition_dict['saturated fat'] = nutrition_dict['saturated fat'] + nutrition_file[key][i]
elif i == 4:
nutrition_dict['carbohydrates'] = nutrition_dict['carbohydrates'] + nutrition_file[key][i]
elif i == 5:
nutrition_dict['sugar'] = nutrition_dict['sugar'] + nutrition_file[key][i]
elif i == 6:
nutrition_dict['protein'] = nutrition_dict['protein'] + nutrition_file[key][i]
elif i == 7:
nutrition_dict['salt'] = nutrition_dict['salt'] + nutrition_file[key][i]
i += 1
for key, value in nutrition_dict.items():
print("The total of {} is: {:.2f}".format(key, value))
nutrition = (value * 100) / total_desired_recipe
print("The amount of {} per 100g is: {:.2f}".format(key, nutrition))
i += 1
所以我的问题是:有没有更好的方法来遍历 Nutrition_dict 键?
我还希望打印语句是“总信息”并遍历所有内容,然后是“每 100g 信息”并遍历所有内容。我不喜欢当前的“总计,每 100 克,总计,每 100 克”
【问题讨论】:
-
这是Code Review 上的一个更好的问题。
标签: python dictionary key