如何将用户的输入添加到 Python 列表中

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21043387/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 21:53:24  来源:igfitidea点击:

How do you add input from user into list in Python

pythonlistshopping

提问by pythonswag

print ('This is your Shopping List')          
firstItem = input('Enter 1st item: ')         
print (firstItem)             
secondItem = input('Enter 2nd item: ')           
print (secondItem)  

How do I make a list of what the user has said then print it out at the end when they have finished?

如何列出用户所说的内容,然后在他们完成后将其打印出来?

Also how do I ask if they have added enough items to the list? And if they say no then it will print out the list of items already stored.

另外我如何询问他们是否在列表中添加了足够的项目?如果他们说不,那么它会打印出已经存储的项目列表。

Thanks, I'm new to this so I don't really know.

谢谢,我是新手,所以我真的不知道。

回答by Oni1

shopList = [] 
maxLengthList = 6
while len(shopList) < maxLengthList:
    item = input("Enter your Item to the List: ")
    shopList.append(item)
    print shopList
print "That's your Shopping List"
print shopList

回答by zhangxaochen

code below allows user to input items until they press enter key to stop:

下面的代码允许用户输入项目,直到他们按回车键停止:

In [1]: items=[]
   ...: i=0
   ...: while 1:
   ...:     i+=1
   ...:     item=input('Enter item %d: '%i)
   ...:     if item=='':
   ...:         break
   ...:     items.append(item)
   ...: print(items)
   ...: 

Enter item 1: apple

Enter item 2: pear

Enter item 3: #press enter here
['apple', 'pear']

In [2]: