2015-12-03 119 views
0

我目前正在形成一項計劃,要求美國世界大賽(棒球)的每一位獲勝者與他們形成2個字典。我選擇的代碼是遵循目標的參數(沒有關鍵; 1904年或2015年的價值,因爲沒有世界系列)我認爲我的問題是缺乏對字典的理解,如果你認爲我濫用功能或價值Id感謝幫助。隨意懲罰,我想學習。詞典中的鍵

def main(): 
    start=1903 
    input_file=open('WorldSeriesResults.txt','r') 
    winners=input_file.readlines() 
    year_dict={} 
    count_dict={} 

好了,所以我已經閱讀了文件並創建了詞典,year_dict爲一年:贏家和count_dict爲勝利者:勝利數。

for i in range(len(winners)): 
     team=winners[i].rstrip("\n") 
     year=start+i  
     if year>= 1904: 
      year += 1 
     if year>= 1994: 
      year += 1 
     year_dict[str(year)] = team 
     if team in count_dict: 
      count_dict[team] += 1 
     else: 
      count_dict[team]=1 

好吧,所以我創建了一個範圍循環以方便字典的處理。文件(現在的列表)被逐行剝離並連接到相應的年份(1-A,2-B,3-C等),同時根據需要跳過1904年和1994年。然後使用搜索search函數來計算每個團隊出現在列表中的次數,然後分別將該數字添加到count_dict。在這一點上,我認爲我已經形成了完美的字典,我在這一點上對他們進行了一次print,看起來我是對的。

while True: 
     year=int(input("Enter a year between 1903-215 excluding 1904 and 1994: "))#prompt user 
     if year == 1904: 
      print("There was no winner that year") 
     elif year == 1994: 
      print("There was no winner that year") 
     elif year<1903 or year>2015: 
      print("The winner of that year in unkown") 
     else: 
      winner=year_dict[year] 
      wins=count_dict[winner] 
      print("The team that won the world series in", year, "was the", winner 
      print("The", winner, "won the world series",wins, "times.") 
      break 

我在這裏提示用戶輸入。我希望這是下一個關鍵。用戶給出了一個輸入,如果它的有效,它應該是用於得到答案的關鍵,但該關鍵似乎不起作用。

回答

1

通過

winner=year_dict[str(year)] 

,因爲你使用的字符串來填充你的字典更換

winner=year_dict[year] 

0

你這個問題很簡單,無論你的字典的keysyear_dict & count_dictstring格式,所以當你查詢你的dictwhile循環,你需要將它們轉換回到string,如下:

while True: 
     year=int(input("Enter a year between 1903-215 excluding 1904 and 1994: "))#prompt user 
     if year == 1904: 
      print("There was no winner that year") 
     elif year == 1994: 
      print("There was no winner that year") 
     elif year<1903 or year>2015: 
      print("The winner of that year in unkown") 
     else: 
      winner=year_dict[str(year)] 
      wins=count_dict[str(winner)] 
      print("The team that won the world series in", year, "was the", winner 
      print("The", winner, "won the world series",wins, "times.") 
      break