Mit der integrierten Bibliothek json
können Sie JSON in Python-Objekte dekodieren. Wenn Sie diese Daten verwenden:
[
{"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"}
]
Notiere die [...]
und ,
in den Daten, so dass es als eine Liste lädt.
Dann könnte das Skript unten die Aufgabe erledigen.
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))
Ich habe Erklärungen in den Kommentaren. Getestet in IDLE 3.6.1.
Was haben Sie bisher versucht? –
Es gibt viele Möglichkeiten, wie Sie das machen könnten und Sie fragen nach einer sehr spezifischen Implementierung, versuchen Sie eine spitzere Frage wie "Wie lese ich Textdateien in Python?" (Obwohl das schon eine Antwort hat: https: //stackoverflow.com/questions/14676265/how-to-read-text-file-into-a-list-or-array-with-python#14676357). Wie willst du sie einlesen? Nur die Punktzahl oder wollen Sie alle Daten? Was weißt du über die Formatierung? –
Offenbar durch Aufruf von 'get_stackoverflow_to_do_all_my_homework()' – donkopotamus