2017-09-25 16 views
-1

-------回答是,我做的是正確的事情,但有一個不同的錯誤,使我認爲這是做錯事情------------------Python:如何向用戶詢問列表的索引

好吧,所以我知道這是超級簡單,但我真的很困惑如何將用戶輸入作爲一個數字,並使用數字從具有該數字的列表中索引。 所以我想要做的是這樣的: 請輸入您的選擇:(用戶輸入1) 您選擇1. 哪一句? (用戶在他們輸入的句子數量的範圍內輸入一個0或任何他們想要的數字)

然後我只想使用它們從列表中輸入的數字和索引。 所以,如果他們進入這兩個句子爲他們的名單: 好 壞

然後,當他們問這句話,說1,我想指數sentenceList [1],並打印回給他們。

但是這需要可縮放到任何數字,所以sentenceList [variable], 但我不知道如何正確地做到這一點。

謝謝,我知道這可能會令人困惑。

#declare variable 
TOTAL_SENTENCES = 5 


def main(): 

#print greeting 
print ('This program will demonstrate lists') 

#establish array sentences 
sentenceList = list() 

#prompt user for how many sentences to store (assume integer, but if 
negative, set to 5) 
TOTAL_SENTENCES = int(input('How many sentences? ')) 
if TOTAL_SENTENCES < 0: 
    TOTAL_SENTENCES = 5 
else: 
    pass 

#store in a list in all lower case letters (assume no period at the end) 
while len(sentenceList) < TOTAL_SENTENCES: 
    userSentence = input('Enter a sentence: ') 
    sentenceList.append(userSentence.lower()) 

#print 5 options for the user to choose from (looping this for the total 
number of sentences) 
for i in range(TOTAL_SENTENCES): 
    print ('Enter 1 to see a sentence\n' 'Enter 2 to see the whole list\n' 
      'Enter 3 to change a sentence\n' 'Enter 4 to switch words\n' 
      'Enter 5 to count letters') 

    #prompt user for their choice 
    userChoice = int(input('Enter your choice: ')) 

    #print their choice back to them 
    print ('You selected choice' ,userChoice) 

    #prompt for which sentence       
    #CHOICE-1 (pull from the list and print the sentence) 
+0

我不確定你在這裏遇到麻煩。你已經將輸入轉換爲一個int,那麼爲什麼你不能把它用作索引呢? –

+0

好的,很抱歉,如果它很混亂。如何使用數字的用戶輸入作爲索引中的數字? –

+0

userInput = 1,sentenceList [userInput] –

回答

0

現在,在你的代碼的最後一行,如果你想從列表中sentenceList拉起了那句話,你可以這樣寫:

print(sentenceList[userChoice-1]) 

注意,我寫userChoice-1。這是因爲人們通常會將句子從1到N編號。但是Python的內部列表編號是從0到N-1。

我希望這能回答你的問題!

+0

在括號中使用'print'表明OP使用Python 3.x,在這種情況下'input'是正確的方法。 – asongtoruin