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?
import json
with open('<yourFile>.json', 'r') as JSON:
json_dict = json.load(JSON)
# Now you can use it like dictionary
# For example:
print(json_dict["username"])
这里有一个简单的片段,它读取字典中的
json
文本文件。注意,json文件必须遵循json标准,因此它必须有"
双引号,而不是'
单引号。您的JSON dump.txt文件:
Python脚本:
JSON是一个数组,里面有一个对象,所以当你读入它时,你会得到一个列表,里面有一个字典。您可以通过访问列表中的项0来访问词典,如下所示:
现在您可以访问存储在数据点中的数据,正如您所期望的那样:
datapoints[0:5][0]
没有达到您的预期。datapoints[0:5]
返回一个新的列表切片,其中只包含前5个元素,然后在其末尾添加[0]
将只从得到的列表切片中获取第一个元素。要得到想要的结果,需要使用的是list comprehension:以下是计算平均值的简单方法:
如果您愿意安装NumPy,那么就更容易:
将
,
运算符与NumPy数组的切片语法一起使用,具有您最初期望的列表切片行为。您可以使用以下选项:
相关问题 更多 >
编程相关推荐