亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何解決 Python 中的 KeyError?

如何解決 Python 中的 KeyError?

Qyouu 2022-04-27 16:14:28
我正在嘗試創建一個預測工具,用于分析給定機場的歷史客流量。分析將基于與機場相關國家的各種 GDP(國內生產總值)的線性回歸。一個人可以輸入獨立變量的名稱,然后從 Excel 文件中選擇該名稱。一旦有人收到“您希望將哪個國家的 GDP 設置為回歸分析的自變量?”的問題,就有可能輸入錯誤的國家/地區。在那種情況下,我會收到一個 KeyError。我正在嘗試使用“try / except”來解決這個問題,但我仍然收到 KeyError(參見第 36-49 行)。我真的很感激一些幫助!謝謝!如果有幫助,這里是 GitHub 鏈接:https ://github.com/DR7777/snowflake (參見 main_file.py 的第 36-49 行)這是我的代碼:我試過使用while循環,for / except,但似乎我太新了,無法理解。# This part saves the first row of the Excel as a list,# so I can give the user a list of all the countries, # if the person types in a country, that's not on the list.loc = ("IMF_Country_GDP_Data.xlsx") wb = xlrd.open_workbook(loc) sheet = wb.sheet_by_index(0) sheet.cell_value(0, 0) list_of_countries = sheet.row_values(0)possible_selection = (list_of_countries[1:]) #This is the list with all the possible countries, without the Excel cell A1#Introductionprint("Hello, welcome to the Air Traffic Forecasting Tool V0.1!")print("Which Country's GDP would you like to set as the independant variable for the Regression Analysis?")Country_GDP = input("Please type your answer here: ")#here we check, if the typed Country is in the listtry:    possible_selection == Country_GDP    print("Your country is on the list.")except KeyError:    print("Oh no! You typed a country, which is not in our database!")    print("Please select one of the countries listed below and try again")    print(possible_selection)#now continuing with the previous codeprint("Ok, I will conduct the analysis based on the GDP of " + str(Country_GDP) + "!")print("Here are your results: ")#here is the rest of the code我想要實現的是:如果一個人輸入了一個國家列表中的名字,程序就會運行回歸。如果該國家/地區不在列表中,我不想收到 KeyError。我想讓程序說:哦不!您輸入的國家/地區不在我們的數據庫中!請選擇下面列出的國家之一,然后再試一次,然后打印 possible_selection 變量,這樣用戶就可以看到他有哪個選項。
查看完整描述

1 回答

?
慕婉清6462132

TA貢獻1804條經驗 獲得超2個贊

根本不需要得到關鍵錯誤。只需使用in.


while True:

    selection = input('Which country?')

    if selection in list_of_countries: 

        print('Your country is on the list')

        break

    else:

        print('You typed an invalid entry, lets try again')


查看完整回答
反對 回復 2022-04-27
  • 1 回答
  • 0 關注
  • 466 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號