我正在嘗試幫助某人從串列中提取設施串列,而無需輸入設施的全名。相反,我認為將數字與每個設施相關聯并允許用戶只需輸入相應的數字即可獲得字串會更容易。例如,如果我有一個“設施 a”、“設施 b”和“設施 c”的串列,如果用戶輸入“0”,“設施 a”會出現,1“設施 b”會出現,等等。我知道我的代碼不正確,但我正在努力根據用戶通過輸入命令輸入的數字來完成這項作業。請參閱下面的代碼。
facilities = ['facility a', 'facility b', 'facility c']
for count, value in enumerate(facilities):
j = (count, value)
print(j) #This is just so the user can see all possible options in the list
f = input('Please enter the corresponding number of the facility you want to select: ')
final_facility = facilities[f] # I know this doesn't work and it wants a number, not a string
print(final_facility)
uj5u.com熱心網友回復:
使用 將輸入轉換為整數int。
準確地說,無論何時你想訪問索引處的元素,int(f)而不是直接傳遞f
uj5u.com熱心網友回復:
默認情況下,input()回傳一個字串。但是,串列索引不能是字串。所以,它需要像這樣
f = int(input('Please enter the corresponding number of the facility you want to select: '))
uj5u.com熱心網友回復:
或者,您可以自動將輸入型別轉換為:
f = int(input('Please ...'))
uj5u.com熱心網友回復:
您需要檢查輸入是否為數字,然后將其轉換為 int。像這樣:
facilities = ['facility a', 'facility b', 'facility c']
for count, value in enumerate(facilities):
j = (count, value)
print(j) #This is just so the user can see all possible options in the list
f = input('Please enter the corresponding number of the facility you want to select: ')
final_facility = 'Please eneter a number' # Prints this if f is not numeric
if f.isnumeric():
final_facility = facilities[int(f)] # I know this doesn't work and it wants a number, not a string
print(final_facility)
uj5u.com熱心網友回復:
facilities = ['facility a', 'facility b', 'facility c']
for count, value in enumerate(facilities):
j = (count, value)
print(j) #This is just so the user can see all possible options in the list
f = input('Please enter the corresponding number of the facility you want to select: ')
final_facility = facilities[int(f)] # Pass int(f) instead of f
print(final_facility)
或者
facilities = ['facility a', 'facility b', 'facility c']
for count, value in enumerate(facilities):
j = (count, value)
print(j) #This is just so the user can see all possible options in the list
f = int(input('Please enter the corresponding number of the facility you want to select: ')) # Typecast your input to int
final_facility = facilities[f]
print(final_facility)
確保處理 ValueErrors 的例外。
uj5u.com熱心網友回復:
就在最終設施之前,寫f=int(f)
那應該解決它。因為,默認情況下,用戶輸入在 python 中是一個字串,所以現在,我們將 f 型別轉換為一個整數來解決它。還可以嘗試使用字典,這將完全消除這個麻煩。同樣要得到答案,在 for 回圈之后你可以直接寫:
print(facilities (int(f)))。
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/339430.html
