2017-11-25 3 views
1

私は、ユーザーが値のリスト(12ヶ月の期間のそれぞれの降雨量)を入力して合計を計算することを可能にするプログラムを作成するように求めているプログラミング・イントロ・プログラミング・クラスの宿題に取り組んでいます。中央値、およびリスト内の最小値と最大値が含まれます。どのように変数の値をその変数の名前に結びつけることができますか?

私はこれまでのところ働いていますが、値が結びついている月の名前をプログラムに印刷させる方法はわかりません。つまり、3月の降水量が最も少ない場合、変数marが表す整数だけでなく、その変数の名前も印刷するように指示するにはどうすればよいですか?私がオンラインで見つけられるものから、リストの代わりに辞書を使うべきだと示唆されています - しかし、私たちは来週まで授業中の辞書をカバーしていません。そして、excersiseが出ている本の章は、私はリストを使ってこれを行う方法を見つけるはずです。ここで

は、これまでの私のコードです:

def main(): 
    jan= float(input('Please enter January rainfall')) 
    feb= float(input('Please enter Februrary rainfall')) 
    mar= float(input('Please enter March rainfall')) 
    apr= float(input('Please enter April rainfall')) 
    may= float(input('Please enter May rainfall')) 
    jun= float(input('Please enter June rainfall')) 
    jul= float(input('Please enter July rainfall')) 
    aug= float(input('Please enter August rainfall')) 
    sep= float(input('Please enter September rainfall')) 
    oct= float(input('Please enter October rainfall')) 
    nov= float(input('Please enter November rainfall')) 
    dec= float(input('Please enter December rainfall')) 
    yearly_rainfall = [jan, feb, mar, apr, may, jun, jul, aug, sep, oct, nov, dec] 
    total = sum(yearly_rainfall) 
    median = total/12 
    print('The total rainfall for the year is', total) 
    print('The average monthly rainfall for the year is', median) 
    print('The month with the lowest rainfall was', min(yearly_rainfall)) 
    print('The month with the highest rainfall was', max(yearly_rainfall)) 


main() 
+0

なぜ月名の別リストを保存できないのですか? –

+0

私はそれについて考えましたが、正しい変数に対応する月の名前を選択する方法をよく分かりません –

+0

あなたの質問を解決するにはさまざまな方法があります。たとえば、リストのドキュメントを読む方法リスト内の値を見つけます。またはあなたのデータストレージを再考して辞書を使うことができます。 @ElijahRyker。 – ahed87

答えて

1

あなたは、単に月の名前を含む別のリストにリスト内の最小値と最大値のインデックスとの関係を持つことができます。

calendarMonthNames = ["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"] 
#Get the index of the min value and use that index value to get the month name. 
print('The month with the lowest rainfall was', min(yearly_rainfall), ', and that month is', calendarMonthNames[yearly_rainfall.index(min(yearly_rainfall))]) 
+0

ありがとう、これは私が知りたかったものです。あなたは素晴らしいです! –

+0

@Elijah投稿の横にあるチェックマークを使用して回答を受け入れることを忘れないでください –

関連する問題