python - 映射策略以计算 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
由成分名称索引的成分。随着成分的迭代,如果成分不在唯一成分图中,则添加该成分,否则增加该成分的数量。最后,数量除以找到成分的次数(我必须明确地保持计数吗?)。您认为这是一个可行的解决方案吗?
解决方案
您可以遍历所有输入,然后在两个默认字典中收集所有必要的信息,您将在最后一步中使用它们来计算平均值。
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}
推荐阅读
- c# - 在 Castle Windsor 中使用 XML 配置注册具有多个泛型类型的接口
- javascript - 覆盖 Object.prototype.get 以防止大型应用程序中的空检查问题
- php - PHP PEAR MAIL,如何发送 Outlook 日历邀请?
- ios - css var 中的相对 URL 在 iOS 上工作错误
- javascript - 为什么onclick在javascript中没有点击就执行?
- windows - 如何在 Windows 10 命令行上使用多个 .exe 版本?
- google-api - 成功登录后,Google Drive(Picker)不显示所有文件
- mongodb - 在 Mongo 中查询空对象
- javascript - 无法打开客户端发送的已保存为原始数据的图像文件
- excel - 尝试调用名字和姓氏列表但返回不匹配错误