简体   繁体   English

如何将用户输入存储到 Python 列表中

[英]How to store user input into list on Python

I'm having a bit of trouble putting user inputs into a list.我在将用户输入放入列表时遇到了一些麻烦。 I basically want the user to input about 5 thing and have each item stored in the list individually.我基本上希望用户输入大约 5 件事,并将每个项目单独存储在列表中。 I then want to display all the input in said list.然后我想显示所述列表中的所有输入。 If anyone can give any bit of guidance it will be greatly appreciated.如果有人可以提供任何指导,将不胜感激。 This is what i have so far:这是我到目前为止:

mylist=[1,2,3,4,5]

print mylist

print"Enter 5 items on shopping list"

for i in mylist:
    shopping=raw_input()

print shopping

I strongly urge you to read through the Python docs which provide you with some basic examples of list operation - open up a shell, and type those examples out for yourself.我强烈建议您通读Python 文档,这些文档为您提供了一些列表操作的基本示例——打开一个 shell,然后自己输入这些示例。 Basically you want to store someone's input into mylist , so there is no need to predefine it with values:基本上,您想将某人的输入存储到mylist ,因此无需使用值预定义它:

mylist=[]

Now you want to prompt a user 5 times (to enter 5 items):现在您要提示用户 5 次(输入 5 个项目):

print "Enter 5 items on shopping list"
for i in xrange(5): # range starts from 0 and ends at 5-1 (so 0, 1, 2, 3, 4 executes your loop contents 5 times)
    shopping = raw_input()
    mylist.append(shopping) # add input to the list

print mylist # at this point your list contains the 5 things entered by user

This is my way of storing input into a list:这是我将输入存储到列表中的方式:

list = []
i = 1
while i < 6:
    a = input("Please enter " + str(i) +  " list : ")
    list.append(a)
    i+=1
print(list)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM