python - 从两个 JSON 数组中获取平均值
问题描述
我有两个 json 提要,我将它们合并到一个文件中。事件和用户。我需要从 users.json 中获取平均年龄,以确定访问主页 (events.json) 的所有不同用户的平均年龄。
示例 JSON 提要事件:
"events": [
{
"name": "Added item to cart",
"timestamp": 1422119921,
"user_id": "5a5598f2-f7db-420e-9b8e-52a9ad694bc1"
},
{
"name": "Visited product page",
"timestamp": 1409554014,
"user_id": "4683c9b6-3c8b-4215-a401-a9bbfde833ee"
}
示例用户供稿:
"age": 27,
"gender": "F",
"device": "android"
},
"712ae3b5-fbf0-4d83-9324-adc06af77d3a": {
"age": 34,
"gender": "F",
"device": "android"
},
我是 python 新手,我相信我在下面的正确轨道上,但不知道下一步该去哪里。任何额外的帮助将不胜感激。
import json
# Opening JSON file
with open('combined.json') as json_file:
data = json.load(json_file)
# for reading nested data [0] represents
# the index value of the list
print(data['events'][0])
print(data['users'][0])
# for printing the key-value pair of
# nested dictionary for looop can be used
print("\nPrinting nested dicitonary as a key-value pair\n")
for i in data['events']:
print("Name:", i['name'])
for i in data ['users']:
print ("Age:", i['age'])
解决方案
您走在正确的轨道上,只需将所有年龄相加并除以用户数量即可。这是一种方法:
import json
# Opening JSON file
with open('combined.json') as json_file:
data = json.load(json_file)
total_age = 0
counter = 0
for k, v in json.load(data['users']).items():
# Add all the ages
total_age += v['age']
counter += 1
print(total_age / counter)
推荐阅读
- spring - 即使出现“ORA-01438:值大于此列允许的指定精度”错误,是否仍会写入一行?
- python - 如何在 Python 中使用 executemany 更新 MySQL 表
- twitter - 是否可以通过 twitter API 检索已删除的推文或已删除的帐户?
- java - ifFile 不识别 csv、pl、sh、xml 文件
- ansible - 如何混淆剧本中的字符串
- c# - c# MRZ TDI1 校验位与校验位号不匹配
- regex - 如何在perl中查找和替换多行文本
- java - JDBi3 UnableToCreateStatementException:没有为限定类型 org.jdbi.v3.core.argument.NullArgument 的“假”注册参数工厂
- c# - 如何使用 Refit 在 dotnet 5 中使用 XOP 处理 XML SOAP?
- python - 在 Python 中解析 GATE 文档的 TextWithNodes 元素