2017-06-29 2 views
0

Modifiziert:Berechnungsschleife Python-Score-Datei

Mit den Noten Datei folgenden Schüler, wie würde ich die Daten laden und score1, score3 in Python zusammenfassen?

{"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"} 

Ausgang:

score1: 70.63 
score3: 22.92 
+0

Was haben Sie bisher versucht? –

+0

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? –

+2

Offenbar durch Aufruf von 'get_stackoverflow_to_do_all_my_homework()' – donkopotamus

Antwort

0

datei.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"} 

Do:

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)) 

Ouput:

score1: 70.63 
score3: 22.92 
0

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.