我正在尝试传入一个 JSON 文件并将数据转换为字典。
到目前为止,这就是我所做的:
import json
json1_file = open('json1')
json1_str = json1_file.read()
json1_data = json.loads(json1_str)
我希望 json1_data
是 dict
类型,但当我使用 检查它时,它实际上是
。 list
类型>类型(json1_data)
我错过了什么?我需要这是一本字典,这样我才能访问其中一个键。
最佳答案
您的 JSON 是一个内部包含单个对象的数组,因此当您读取它时,您会得到一个包含字典的列表。您可以通过访问列表中的第 0 项来访问您的字典,如下所示:
json1_data = json.loads(json1_str)[0]
现在您可以按预期访问存储在 datapoints 中的数据:
datapoints = json1_data['datapoints']
I have one more question if anyone can bite: I am trying to take the average of the first elements in these datapoints(i.e. datapoints[0][0]). Just to list them, I tried doing datapoints[0:5][0] but all I get is the first datapoint with both elements as opposed to wanting to get the first 5 datapoints containing only the first element. Is there a way to do this?
datapoints[0:5][0]
不符合您的预期。 datapoints[0:5]
返回一个仅包含前 5 个元素的新列表切片,然后在其末尾添加 [0]
将只取第一个元素 来自结果列表切片。您需要使用 list comprehension 来获得所需的结果:
[p[0] for p in datapoints[0:5]]
这是计算平均值的简单方法:
sum(p[0] for p in datapoints[0:5])/5. # Result is 35.8
如果您愿意安装 NumPy ,那就更简单了:
import numpy
json1_file = open('json1')
json1_str = json1_file.read()
json1_data = json.loads(json1_str)[0]
datapoints = numpy.array(json1_data['datapoints'])
avg = datapoints[0:5,0].mean()
# avg is now 35.8
将 ,
运算符与 NumPy 数组的切片语法结合使用,可以实现您最初期望的列表切片行为。
https://stackoverflow.com/questions/19483351/