5月14日の演習問題の iii. で昨年の松江市の気温データのリストを使用しました.今回はそれを CSV 形式にしたものを用意しましたので,そのデータを読み込んで,同じように最高気温と最低気温を求めるプログラムを作成しましょう.
The highest temperature: August 22, 38.2 degree Celsius The lowest temperature: January 17, -2.7 degree Celsius |
ポイントは読み込んだデータを float を使用して実数にするところでしょうか.2次元のリストで,内側のリストの要素の個数もそれぞれ違いますので,len 関数を使用して各要素の個数分の反復処理で実現しましょう.
解答用紙を使用する際には,学生番号と名前の記入も忘れないでください.さらに,解答用紙自体がPythonのプログラムとなっていますので,実行してエラーの無いことを確認してから提出してください. 指定の解答用紙を使用していない,実行時にエラーが出る,学生番号と名前が無い,というような答案は提出されても採点しません.注意してください. |
解答例
# ############################# # # プログラミング入門II 宿題 2025.6.18 # 学生番号: s246099 # 氏名: 松江 花子 # # ############################# from csv import * print('Student number: s246099') print() month = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'] mn = 100 mx = 0 with open('temp_data.csv', 'r') as f: temp = reader(f) txtdata = [n for n in temp] temp_data = [[float(txtdata[i][j]) for j in range(len(txtdata[i]))] \ for i in range(24)] for i in range(24): tmax = max(temp_data[i]) tmin = min(temp_data[i]) if tmax > mx: mx = tmax d_max = temp_data[i].index(tmax) m_max = i if tmin < mn: mn = tmin d_min = temp_data[i].index(tmin) m_min = i print(f'The highest temperature: {month[m_max // 2]} {d_max + 1}, {mx} degree Celsius') print(f'The lowest temperature: {month[m_min // 2]} {d_min + 1}, {mn} degree Celsius') print('\n------------------------\n') |