Ermitteln Sie den Maximalwert pro Gruppe aus der CSV-DateiPython

Python-Programme
Anonymous
 Ermitteln Sie den Maximalwert pro Gruppe aus der CSV-Datei

Post by Anonymous »

Ich habe eine CSV-Datei mit Spalten wie:

Code: Select all

student_id,subject,score
S001,Math,85
S001,Physics,92
S001,Chemistry,78
S002,Math,88
Was ich tun möchte ist:
  • Zeilen nach einer bestimmten student_id filtern
  • Die höchste Punktzahl finden für diesen Studenten
  • Das entsprechende Fach abrufen
Ich bin Ich kann die CSV-Datei lesen, bin mir aber nicht sicher, wie ich die maximale Punktzahl am besten verfolgen und den entsprechenden Wert zurückgeben kann.
Was wäre eine saubere und anfängerfreundliche Möglichkeit, dies in Python zu tun?
Update:
Das habe ich nach 2 Stunden. Gibt es etwas, das mir noch fehlt und das ich verbessern könnte?

Code: Select all

    # QUESTION: Highest Score Finder
# Goal: Find which subject a student did best in

# Step 1: Import the csv module to read CSV (Comma-Separated Values) files
import csv

# Step 2: Define a FUNCTION - a reusable block of code
# Functions are like recipes - you define them once, use them many times
# student_id is the INPUT (parameter) the function needs
def highest_score(student_id):
# Variables to track the best score found so far
# None means "no value yet"
best_subject = None
# Start with -1 so any real score will be higher
best_score = -1

# Step 3: Open and read the CSV file
with open("scores.csv", "r") as f:
# DictReader reads CSV and treats each row as a dictionary
# A dictionary is like a real dictionary: you look up a word (key)
# and get its definition (value)
# Example: row["subject"] gives you the subject column value
reader = csv.DictReader(f)

# Step 4: Look at each row (each student's score for one subject)
for row in reader:
# Check if this row is for the student we're looking for
if row["student_id"] == student_id:
# Convert score from text to number
score = int(row["score"])

# Is this score better than the best we've seen?
if score > best_score:
# Yes! Update our best score and subject
best_score = score
best_subject = row["subject"]

# Step 5: Return the answer (give it back to whoever called the function)
return best_subject

# Step 6: Call the function and print results
# The function runs, finds the answer, and returns it to print()
print(highest_score("S001"))  # Will print "Physics"
print(highest_score("S003"))  # Will print "Chemistry"

Quick Reply

Change Text Case: 
   
  • Similar Topics
    Replies
    Views
    Last post