Python:如何向用户请求列表的索引
-------回答:原来我做的是对的,但有一个不同的错误,让我认为这是错误的------------------ 好吧,我知道这非常简单,但我真的很困惑,如何将用户输入作为一个数字,并使用该数字从列表中索引该数字。 所以我想做的是: 输入您的选择:(用户输入1) 你选择1。 哪句话?(用户在输入的句子数量范围内输入0或任意数字) 然后我只想使用他们输入的号码,并从列表中索引。 因此,如果他们在列表中输入以下两句话: 好的 坏的 然后,当他们问哪个句子,说1,我想索引句子列表[1],然后打印回给他们 但这需要能够扩展到任何数字,因此sentenceList[变量], 但我不知道如何正确地做到这一点 谢谢,我知道这可能会让人困惑Python:如何向用户请求列表的索引,python,if-statement,while-loop,user-input,Python,If Statement,While Loop,User Input,-------回答:原来我做的是对的,但有一个不同的错误,让我认为这是错误的------------------ 好吧,我知道这非常简单,但我真的很困惑,如何将用户输入作为一个数字,并使用该数字从列表中索引该数字。 所以我想做的是: 输入您的选择:(用户输入1) 你选择1。 哪句话?(用户在输入的句子数量范围内输入0或任意数字) 然后我只想使用他们输入的号码,并从列表中索引。 因此,如果他们在列表中输入以下两句话: 好的 坏的 然后,当他们问哪个句子,说1,我想索引句子列表[1],然后打印回给他
#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)
#声明变量
句子总数=5
def main():
#打印问候语
打印('此程序将演示列表')
#建立一组句子
句子列表=列表()
#提示用户存储多少个句子(假设为整数,但如果
负数,设置为5)
总句子数=int(输入(“多少个句子”)
如果总句子数<0:
句子总数=5
其他:
通过
#以所有小写字母存储在列表中(假设末尾没有句点)
而len(句子列表)<句子总数:
UserSession=input('输入一个句子:')
sentenceList.append(userSession.lower())
#打印5个选项供用户选择(循环此选项以获得总数
(句子数)
对于范围内的i(总句子数):
打印('输入1查看句子\n''输入2查看整个列表\n'
'输入3以更改句子\n''输入4以切换单词\n'
'输入5以计数字母')
#提示用户进行选择
userChoice=int(输入('输入您的选择:'))
#将他们的选择打印回给他们
打印('youselectchoice',userChoice)
#提示哪句话
#选项1(从列表中选择并打印句子)
现在,在代码的最后一行,如果你想从列表句子列表中提取一个句子,你可以写:
print(sentenceList[userChoice-1])
请注意,我编写了userChoice-1
。这是因为人们通常将句子从1到N进行编号。但是Python的内部列表编号是从0到N-1
我希望这能回答你的问题 我不知道你在哪里遇到麻烦。您已经将输入转换为int,那么为什么不能将其用作索引呢?好的,如果让人困惑的话,很抱歉。如何使用用户输入的数字作为索引中的数字?userInput=1,sentenceList[userInput]呃,完全一样。你试过了吗?是的,编辑了文章的顶部,我做得不错,但有一个错误让我觉得我做得不对。括号中使用print
,表明OP使用的是Python 3.x,在这种情况下input
是正确的方法。