编写一个能读取txt文件中一周的气温数据,计算其统计值(最高气温、最低气温、每天平均气温、全周平均气温)的小程序。
时间: 2024-03-12 16:47:14 浏览: 34
当然可以,以下是一个Python程序实现你的需求:
```python
# 打开文件,读取气温数据
with open('temperatures.txt', 'r') as f:
temperatures = f.readlines()
# 将气温数据转换为整数
temperatures = [int(temp.strip()) for temp in temperatures]
# 计算最高气温、最低气温和每天平均气温
max_temp = max(temperatures)
min_temp = min(temperatures)
avg_temps = [sum(temperatures[i:i+24])/24 for i in range(0, len(temperatures), 24)]
# 计算全周平均气温
overall_avg_temp = sum(temperatures) / len(temperatures)
# 将结果输出到新文件中
with open('temperature_stats.txt', 'w') as f:
f.write(f"最高气温: {max_temp}\n")
f.write(f"最低气温: {min_temp}\n")
f.write("每天平均气温:\n")
for i, avg_temp in enumerate(avg_temps):
f.write(f"星期{i+1}: {avg_temp}\n")
f.write(f"全周平均气温: {overall_avg_temp}")
```
请确保在运行程序前,将气温数据保存到名为`temperatures.txt`的文件中,并将该文件与程序放在同一目录下。程序将计算最高气温、最低气温、每天平均气温和全周平均气温,并将结果输出到名为`temperature_stats.txt`的文件中。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![cs](https://img-home.csdnimg.cn/images/20210720083646.png)