2016-04-15 6 views
1

pythonを使って課題を完成しようとしています。 ディクショナリを使用して.txtファイルを解析し、時間と温度を分離することを目標としています。それらを辞書に置き、最も高い温度とそれに対応する時間を見つける。Pythonプログラミング:辞書を使ってデータを分離する

私は割り当てを完了しましたが、印刷を最高にする方法を理解できません。代わりに私はトップ3を印刷しています。

pycharm output

fname = raw_input("Enter the file name: ") 

try: 
    fhand = open(fname) 
except: 
    print "The file can not be opened." 
    exit() 

climate = dict()  #creates dictionary 

count = 0 
largest = None # Iteration variable to find highest temp 

high = 0 
for line in fhand: 
    count += 1    #count variable to get rid of line 1 
    if count == 1:  #may be causing it to iterate 3x???? 
     continue 

    words = line.split()   # splits into tokens 
    time = words[0] + words[1]  # combines time and am/pm 
    climate[time] = words[2]  # matches time to temp making key-value pair 

for key in climate: 
     if climate[key] > largest: # Iterates through key-value's finding largest and placing it in largest container 
      largest = climate[key] 

      print 'The highest temperatures occurred at', key, 'reaching', largest, 'Fahrenheit.' 

fhand.close() 
+1

は、それがループの外のスコープにあるので、ループの前に 'key'を定義し、ループ内で印刷されません。 'for'ループが終了した後に出力します。 – sberry

+0

ようこそ。質問の構造を編集して少し明確にしました。あなたのIDE出力に画像リンクを投稿する代わりに、その質問を編集して質問のテキストとして出力を表示することをお勧めします。 @sberryの提案もポイントです。 – paisanco

答えて

0

これは、あなたが欲しいものを行う必要があります。

high_key = None 
largest = 0 
for key in climate: 
     if climate[key] > largest: # Iterates through key-value's finding largest and placing it in largest container 
      largest = climate[key] 
      high_key = key 

if high_key: 
    print 'The highest temperatures occurred at', high_key, 'reaching', largest, 'Fahrenheit.' 
+0

ありがとうございます。それは私の邪魔になっていた。値を切り替えるために必要な私の変数「高」と「最大」は、ゼロとなしの違いを教えてください。残りの部分は何が起こっているのか理解しています。 –

+0

最大値を0に設定すると、温度が正であると想定されるため、一時的な値は初期値を上書きします。私は、負の値を扱うので、Noneはうまくいくと思う。個人的には、私は '' most = float( ' - inf') 'を初期化する方が望ましいと思います。 – Philip

+0

ああ大丈夫です。ありがとうございました。私はそれと一緒に遊んでいきます。 –

関連する問題