2016-04-15 20 views
1

我想完成使用python的任務。 目標是使用字典來分析.txt文件並隔離時間和溫度。將它們放在字典中,然後找到最高溫度和相應的時間。Python的編程:使用字典來隔離數據

我已完成作業,但是我無法弄清楚如何使其僅打印最高。相反,我打印前三名。

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

歡迎來到SO。我編輯了這個問題的結構,使其更加清晰。我建議不要將圖像鏈接發佈到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假定溫度爲正值,這樣一些溫度將超過初始值。我認爲「無」會更好,因爲它會處理負值。就我個人而言,我寧願初始化'largest = float(' - inf')',因爲我認爲這意圖更清晰。 – Philip

+0

啊,好吧,這是有道理的。謝謝。我會繼續玩。 –