我想完成使用python的任務。 目標是使用字典來分析.txt文件並隔離時間和溫度。將它們放在字典中,然後找到最高溫度和相應的時間。Python的編程:使用字典來隔離數據
我已完成作業,但是我無法弄清楚如何使其僅打印最高。相反,我打印前三名。
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()
循環之前定義'key'所以它的範圍是外循環,而不要在循環中打印,在'for'循環結束後打印。 – sberry
歡迎來到SO。我編輯了這個問題的結構,使其更加清晰。我建議不要將圖像鏈接發佈到IDE輸出,而是編輯問題以將問題的輸出顯示爲文本。還有@sberry的建議是關鍵。 – paisanco