Python:如何向用户询问列表的索引
问题描述:
-------回答是,我做的是正确的事情,但有一个不同的错误,使我认为这是做错事情------------------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)
答
现在,在你的代码的最后一行,如果你想从列表中sentenceList
拉起了那句话,你可以这样写:
print(sentenceList[userChoice-1])
注意,我写userChoice-1
。这是因为人们通常会将句子从1到N编号。但是Python的内部列表编号是从0到N-1。
我希望这能回答你的问题!
+0
在括号中使用'print'表明OP使用Python 3.x,在这种情况下'input'是正确的方法。 – asongtoruin
我不确定你在这里遇到麻烦。你已经将输入转换为一个int,那么为什么你不能把它用作索引呢? –
好的,很抱歉,如果它很混乱。如何使用数字的用户输入作为索引中的数字? –
userInput = 1,sentenceList [userInput] –