使用內置庫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中測試。
到目前爲止您嘗試了什麼? –
有很多方法可以解決這個問題,你需要一個非常具體的實現,試着問一個更加尖銳的問題,比如「如何將文本文件讀入python」(儘管它已經有了答案:https: //stackoverflow.com/questions/14676265/how-to-read-text-file-into-a-list-or-array-with-python#14676357)。你希望他們如何閱讀?只是分數還是你想要所有的數據?你對格式有什麼瞭解? –
顯然通過調用'get_stackoverflow_to_do_all_my_homework()' – donkopotamus