修改:
使用以下学生的分数文件,我如何加载数据并在Python中总结score1
,score3
?
{"id": "1","student":"John", "dt": "1997-01-01 07:00:02", "score1": "38.28"}
{"id": "2", "student":"Jane", "dt": "1997-01-01 07:00:02", "score1": "32.35"}
{"id": "3", "student":"Richard", "dt": "1997-01-10 10:00:00", "score3": "22.92"}
输出:
score1: 70.63
score3: 22.92
答案 0 :(得分:0)
<强> file.txt的强>:
{"id": "1","student":"John", "dt": "1997-01-01 07:00:02", "score1": "38.28"}
{"id": "2", "student":"Jane", "dt": "1997-01-01 07:00:02", "score1": "32.35"}
{"id": "3", "student":"Richard", "dt": "1997-01-10 10:00:00", "score3": "22.92"}
执行:
import json
scores = dict()
with open('file.txt') as filename:
for line in filename.readlines():
data = json.loads(line)
score = [key for key in data.keys() if key.startswith('score')]
if len(score) == 0:
continue
score = score[0]
if score not in scores:
scores[score] = 0
scores[score] += float(data[score])
for k, v in scores.items():
print('{}: {}'.format(k, v))
输出继电器:
score1: 70.63
score3: 22.92
答案 1 :(得分:0)
使用内置库json
,您可以将JSON解码为Python对象。
如果您使用此数据:
[
{"id": "1","student":"John", "dt": "1997-01-01 07:00:02", "score1": "38.28"},
{"id": "2", "student":"Jane", "dt": "1997-01-01 07:00:02", "score1": "32.35"},
{"id": "3", "student":"Richard", "dt": "1997-01-10 10:00:00", "score3": "22.92"}
]
请注意数据中的[...]
和,
,以便将其作为列表加载。
然后下面的脚本可以完成这项工作。
import json
from math import fsum
data = json.load(open("data.json")) # Load the data
sums = {}
for person in data: # Loop over pieces of data
# Add any names starting with "score" to sums
for key in person.keys(): # Loop over names
if not key[:5] == "score":
continue # No, not starting with score, skip it
# Use math.fsum to add the value known to the score, and set it.
sums[key] = fsum([sums.get(key, 0.0), float(person[key])])
for k, v in sums.items():
# Print out the data
print("%s: %.02f" % (k, v))
我在评论中添加了解释。在IDLE 3.6.1中测试。