【问题标题】:Is there a better way to iterate through the keys in a dictionary inside a loop?有没有更好的方法来遍历循环内字典中的键?
【发布时间】: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 克”

【问题讨论】:

标签: python dictionary key


【解决方案1】:

有,您可能只想zip nutrition_dict 键与nutrition_file 中每种食物的值:

for k, *v in zip(nutrition_dict, *nutrition_file.values()):
    print(k, v)

kcal [24, 884, 25]
kj [100, 3701, 105]
fat [0.2, 100, 0]
saturated fat [0, 13.8, 0]
carbohydrates [5.7, 0, 8.6]
sugar [2.4, 0, 2.4]
protein [1, 0, 0.4]
salt [0.005, 0.005, 0.0025]

那么你需要做的就是收集总数:

for k, *v in zip(nutrition_dict, *nutrition_file.values()):
    nutrition_dict[k] = sum(v)


nutrition_dict
{'kcal': 933, 'kj': 3906, 'fat': 100.2, 'saturated fat': 13.8, 'carbohydrates': 14.3, 'sugar': 4.8, 'protein': 1.4, 'salt': 0.0125}

【讨论】:

  • 谢谢!这个解决方案非常简单。我需要了解有关 zip 的更多信息
【解决方案2】:

您正在寻找的是枚举,它可以让您(在这种情况下)浏览字典的键,同时按顺序对它们进行编号。完整的解决方案是

for index, key in enumerate(nutrition_dict):
    for ingredient_name, ingredient_amount in amount_of_ingredients.items():
        nutrition_dict[key] += ingredient_amount * nutrition_file[ingredient_name][index]

    print("The total of {} is: {:.2f}".format(key, nutrition_dict[key]))
    nutrition = (nutrition_dict[key] * 100) / total_desired_recipe
    print("The amount of {} per 100g is: {:.2f}".format(key, nutrition))

顺便说一句,kJ 和 kcal 是不同单位的相同数量(系数是 4.184),因此无需同时跟踪两者。

【讨论】:

  • 感谢 kJ 和 kcal 之间的澄清!即使它是由用户提供的,我也会对其进行更改,因此他们无需找到额外的价值。我喜欢这种方法,因为我对 enumerate 比对 zip 更熟悉,所以我会尝试一下。
【解决方案3】:

在迭代方面,Python 有许多简化列表处理的好方法。事实上,您的大部分循环代码都可以通过消除其他编程语言的一些典型“开销”来实现:

for food_type in nutrition_file:
    for index, metric in enumerate(nutrition_dict):
        nutrition_dict[metric] += nutrition_file[food_type][index]

    # Unchanged from OP's example
    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))

【讨论】:

  • 感谢您的澄清和示例。是的,我开始明白你的意思与其他语言的开销有关。有时我会因此而使事情复杂化。
猜你喜欢
  • 2019-09-30
  • 1970-01-01
  • 2022-08-05
  • 2013-10-31
  • 1970-01-01
  • 1970-01-01
  • 2021-08-27
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多