首页 > 解决方案 > 映射策略以计算 JSON 对象数组的平均值

问题描述

我有一个 JSON 对象数组,如下所示:

{
    "recipes": [    
    {
        "name":"recipe-name-1", 
        "ingredients": [
            { "amount": 300, "unit": "g", "ingredient": "ingredient-1" },
            { "amount": 250, "unit": "g", "ingredient": "ingredient-2"},
            { "amount": 100, "unit": "g", "ingredient": "ingredient-3"}
        ]
    },
    {
        "name":"recipe-name-2", 
        "ingredients": [
            { "amount": 350, "unit": "g", "ingredient": "ingredient-1" },
            { "amount": 50, "unit": "g", "ingredient": "ingredient-3"},
            { "amount": 120, "unit": "g", "ingredient": "ingredient-4"}
        ]
    }

等等。

我正在尝试计算每种成分在不同食谱中的平均含量。实现这一目标的最佳方法是什么?我正在考虑构建一个Map由成分名称索引的成分。随着成分的迭代,如果成分不在唯一成分图中,则添加该成分,否则增加该成分的数量。最后,数量除以找到成分的次数(我必须明确地保持计数吗?)。您认为这是一个可行的解决方案吗?

标签: pythonjson

解决方案


您可以遍历所有输入,然后在两个默认字典中收集所有必要的信息,您将在最后一步中使用它们来计算平均值。

from collections import defaultdict
       
counts = defaultdict(int)
amounts = defaultdict(int)

recipes = data['recipes']
for recipe in recipes:
    for ingredient_info in recipe['ingredients']:
        ingredient = ingredient_info['ingredient']
        counts[ingredient] += 1
        amounts[ingredient] += ingredient_info['amount']
        
average_amounts = {}
for key in counts.keys():
    average_amounts[key] = amounts[key] / counts[key]
    
print(average_amounts)

输出:

{'ingredient-1': 325.0,
 'ingredient-2': 250.0,
 'ingredient-3': 75.0,
 'ingredient-4': 120.0}

推荐阅读