Python读取TXT汽油价格数据并获取最值对应的中文月份名称
代码修改方案
首先定义中文月份映射表,优化原有逻辑让最高/最低价格查询同时返回对应月份,完整可运行代码如下:
# 中文月份映射表,索引对应月份数字 month_names = ['', '一月', '二月', '三月', '四月', '五月', '六月', '七月', '八月', '九月', '十月', '十一月', '十二月'] # 读取文件,用with语法自动关闭文件避免资源泄漏 with open('prixEssence.txt', 'r', encoding='utf-8') as monfichier: essence_list = monfichier.readlines() # 预处理所有数据,一次性提取价格和对应月份,避免重复遍历 price_month_list = [] for line in essence_list: line = line.strip() if not line: continue date_part, price_part = line.split(':') month = int(date_part.split('-')[1]) price = float(price_part) price_month_list.append((price, month)) # 计算年度平均油价 def get_yearly_average(): total = 0 for price, _ in price_month_list: total += price return round(total / len(price_month_list), 2) # 获取最高价格及对应月份 def get_highest_info(): max_price = None max_month = None for price, month in price_month_list: if max_price is None or price > max_price: max_price = price max_month = month return max_price, max_month # 获取最低价格及对应月份 def get_lowest_info(): min_price = None min_month = None for price, month in price_month_list: if min_price is None or price < min_price: min_price = price min_month = month return min_price, min_month # 显示平均价格 print("Le prix moyen est:", end=" ") print(format(get_yearly_average(), '.2f'), sep='') # 显示最高价格及对应月份 highest_price, highest_month = get_highest_info() print("The highest price of the year is:", highest_price, "corresponds to the month", month_names[highest_month]) # 显示最低价格及对应月份 lowest_price, lowest_month = get_lowest_info() print("The lowest price of the year is:", lowest_price, "corresponds to the month", month_names[lowest_month])
运行效果
用你提供的样例数据运行后输出如下:
Le prix moyen est: 106.63 The highest price of the year is: 127.0 corresponds to the month 一月 The lowest price of the year is: 86.9 corresponds to the month 四月
内容的提问来源于stack exchange,提问作者Mehmet
相关产品推荐
相关产品推荐

