Python新手求助:如何将每日气温数据聚合为以月份为键的字典?
Hey there! No need to apologize at all—we all start somewhere, and breaking down problems like this is how we learn. Let's walk through how to solve this task without relying on pandas or numpy.
Step 1: Define Assumptions About Your Data
First, let's assume your daily temperature data is stored in a text file (e.g., daily_temps.txt) with one entry per line, formatted like this (adjust if your actual data uses a different structure):
YYYY-MM-DD,min_temp,avg_temp,max_temp
2023-01-01,5.2,10.1,14.8
2023-01-02,4.5,9.7,15.3
...
Step 2: Initialize the Temperature Dictionaries
We'll start by creating our three target dictionaries, each pre-populated with month numbers 1-12 as keys and empty lists as initial values:
# Initialize dictionaries with months 1-12 and empty lists for temps MinT = {month: [] for month in range(1, 13)} AvgT = {month: [] for month in range(1, 13)} MaxT = {month: [] for month in range(1, 13)}
Step 3: Read and Process the Data File
Next, we'll open the file, parse each line, extract the month and temperature values, then append each temperature to the corresponding month's list in our dictionaries:
# Open the data file (update the file path to match your actual file location) with open('daily_temps.txt', 'r') as file: # Skip the header line if your file includes one header = file.readline() for line in file: # Clean up the line and split into components line_parts = line.strip().split(',') # Skip malformed lines that don't have all 4 required values if len(line_parts) != 4: continue date_str, min_temp_str, avg_temp_str, max_temp_str = line_parts # Extract month from the date string (YYYY-MM-DD → grab the 2nd element) month = int(date_str.split('-')[1]) try: # Convert temperature strings to numerical values min_temp = float(min_temp_str) avg_temp = float(avg_temp_str) max_temp = float(max_temp_str) # Add temps to their respective month lists MinT[month].append(min_temp) AvgT[month].append(avg_temp) MaxT[month].append(max_temp) except ValueError: # Skip lines with invalid temperature values print(f"Skipping invalid line: {line.strip()}")
Step 4: Check Your Results
Once the script runs, you can verify the output by accessing specific months. For example, to see all March (month 3) average temperatures:
print("March average temperatures:", AvgT[3])
Quick Tips for Adaptation:
- File Path: If your data file isn't in the same folder as your script, use the full absolute path (e.g.,
C:/data/daily_temps.txton Windows or/home/user/data/daily_temps.txton Linux/macOS). - Data Format Changes: If your data uses spaces instead of commas as separators, replace
split(',')withsplit(). If your date format is different (e.g., DD/MM/YYYY), adjust the month extraction logic to grab the correct part of the date string. - Error Handling: The try-except block and line length check help prevent crashes if your dataset has messy or incomplete lines—always a good practice for real-world data!
内容的提问来源于stack exchange,提问作者Breegan Andersen

