简体   繁体   English

如何在类似 JSON 格式的文件中找到平均值?

[英]How to find average of values in file with JSON-like format?

I am currently recording latency of some write requests to the database just as a part of my internship.作为实习的一部分,我目前正在记录一些对数据库的写入请求的延迟。 There are literally thousands of values like this that gets saved locally in a file named latency.json (I know this is not correct JSON format), but anyways my question is I just need to find the average value of these, and I am supposed to write a python program for this and I have no idea because I am very very new to python.实际上有成千上万个这样的值在本地保存在一个名为latency.json的文件中(我知道这不是正确的JSON格式),但无论如何我的问题是我只需要找到这些的平均值,我应该为此编写一个 python 程序,我不知道,因为我对 python 非常陌生。

I watched a few videos to but it is not helpful because I don't know how to isolate only the latency value.我看了一些视频,但没有帮助,因为我不知道如何仅隔离延迟值。

{"Latency": 0.05749578899849439, "Date & Time": "2021-03-10T20:50:07.132809"}
{"Latency": 0.03988014299829956, "Date & Time": "2021-03-10T20:50:07.673860"}
{"Latency": 0.055852558005426545, "Date & Time": "2021-03-10T20:50:08.230857"}
{"Latency": 0.04969122799957404, "Date & Time": "2021-03-10T20:50:08.781738"}
{"Latency": 0.04796638499828987, "Date & Time": "2021-03-10T20:50:09.330938"}
{"Latency": 0.043185365000681486, "Date & Time": "2021-03-10T20:50:10.022725"}
{"Latency": 0.0398543819974293, "Date & Time": "2021-03-10T20:50:10.563757"}

If the format is JSON Lines then you might want to try this:如果格式是JSON Lines那么你可能想试试这个:

import json

with open("lines.jsonl") as lines:
    d = [json.loads(line) for line in lines.readlines()]
    print(f"Average for {len(d)} requests: {sum(i['Latency'] for i in d) / len(d)}")

Output: Output:

Average for 7 requests: 0.04770369285688503

Simple approach should work:简单的方法应该有效:

import json

s = 0
n = 0
for line in open('data_file.dat'):
    line = line.strip()
    if line == "":
        continue
    d = json.loads(line)
    n += 1
    s += d["Latency"]

print(s/n)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM