如何将气象数据元组列表按年份拆分为年度数据块?
按年份拆分天气历史数据的解决方案
你的代码问题在于用列表all_years_data只存储了年份,没有关联对应天气数据。要实现按年份整合数据,用字典更合适——以年份为键,对应值存该年份的所有天气数据条目。
修正后的代码示例
from typing import List, Tuple, Dict # 定义数据类型(可选,让代码结构更清晰) WeatherEntry = Tuple[Tuple[int, int, int], float, float, float] YearlyWeatherData = Dict[int, List[WeatherEntry]] # 初始化存储结构:键是年份,值是该年的所有数据条目 all_years_data: YearlyWeatherData = {} for entry in weather_history: # 提取当前条目的年份 year = entry[0][0] # 检查年份是否已在字典中,不在则创建空列表 if year not in all_years_data: all_years_data[year] = [] # 将当前数据条目添加到对应年份的列表中 all_years_data[year].append(entry)
代码说明
- 用字典替代原列表,每个年份对应一个专属列表,完整保留该年所有
((year,month,day),precip,tmin,tmax)格式的数据 - 遍历过程中直接关联年份与对应数据,无需单独拆解字段(如果需要单独处理字段,也可以拆解后重新组合再添加)
如果你需要存储拆解后的字段
比如想把每个年份的数据存成[(month, day, precip, tmin, tmax), ...]的格式,代码可以改成这样:
all_years_data: Dict[int, List[Tuple[int, int, float, float, float]]] = {} for (year, month, day), precip, tmin, tmax in weather_history: if year not in all_years_data: all_years_data[year] = [] all_years_data[year].append((month, day, precip, tmin, tmax))
如何使用结果
之后你可以通过年份直接获取对应整年的数据,比如:
# 获取2020年的所有数据 data_2020 = all_years_data.get(2020, []) for item in data_2020: print(item)
内容的提问来源于stack exchange,提问作者Kendall Donahoe
相关产品推荐
相关产品推荐

