如何实现max_latitude函数计算观测对象的年度最大纬度
实现max_latitude函数获取年度最大纬度
先修正原代码的一处错误
Obs类的__init__方法中,调用year_out_of_time时需使用实例方法的调用方式,原代码self.year = year_out_of_time(self)会报错,应改为:
self.year = self.year_out_of_time()
max_latitude函数实现方案
我们需要先按年份分组记录每个年份的最大纬度,再按照years函数返回的排序后年份列表提取对应最大值,保证输出的纵坐标与年份顺序完全匹配:
def max_latitude(observations): # 用字典存储每个年份的最大纬度,初始值设为极小值 year_max_lat = {} for obs in observations: year = obs.year # 若年份未记录,或当前观测纬度更大,则更新该年份的最大纬度 if year not in year_max_lat or obs.latitude > year_max_lat[year]: year_max_lat[year] = obs.latitude # 按照排序后的年份列表,提取对应的最大纬度值 sorted_years = years(observations) return [year_max_lat[year] for year in sorted_years]
完整可运行代码片段
修正后的Obs类和完整函数实现:
import matplotlib.pyplot as plt # 补充原代码缺失的plt导入 class Obs: def __init__(self, latitude, longitude, time, quantity): self.latitude = latitude self.longitude = longitude self.time = time self.quantity = quantity # 修正实例方法调用方式 self.year = self.year_out_of_time() def year_out_of_time(self): date, time = self.time.split("T") year, month, day = date.split("-") return int(year) def read_data(filename): observations = [] try: with open(filename, "r") as f: next(f) # 跳过首行表头 for line in f: if line.endswith("Artportalen\n"): latitude, longitude, time, quantity, Artportalen = line.split(",") else: latitude, longitude, time, quantity = line.split(",") latitude = float(latitude) longitude = float(longitude) quantity = int(quantity.strip()) time = time.strip("Z") observations.append(Obs(latitude, longitude, time, quantity)) except Exception as e: print("Error:", e) return observations def years(observations): out = [] for obs in observations: if obs.year not in out: out.append(obs.year) return sorted(out) def max_latitude(observations): year_max_lat = {} for obs in observations: year = obs.year if year not in year_max_lat or obs.latitude > year_max_lat[year]: year_max_lat[year] = obs.latitude sorted_years = years(observations) return [year_max_lat[year] for year in sorted_years] def plot_data(observations): xpoints = years(observations) ypoints = max_latitude(observations) plt.title("年度最大纬度") plt.xlabel("年份") plt.ylabel("最大纬度") plt.scatter(xpoints, ypoints) plt.show()
说明
- 字典
year_max_lat用于高效记录各年份的最大纬度,仅需遍历一次观测数据即可完成统计,时间复杂度为O(n) - 最后通过排序后的年份列表生成结果,确保与
years函数返回的X轴年份顺序完全对应 - 补充了原代码缺失的
matplotlib.pyplot导入,并适配了中文图表标题
内容的提问来源于stack exchange,提问作者pythonhelpneeded
相关产品推荐
相关产品推荐

