繁体   English   中英

将用户输入输入到Python中的预定义列表中

[英]Input User Inputs into a pre-defined list in Python

我是编程新手,正在尝试根据Python 2.5中的用户输入更新预先建立的列表。

这正是我想做的事情:

我有用户必须选择的各种项目...让我们以以下示例为例:

item1 = [1,2,3,4]
item2 = [2,3,4,5]

我让用户通过使用raw_input选择哪个项目:

item_query = raw_input("Which item do you want?: ")

一旦他们选择了合适的物品,我想将相应的物品(以及相应列表中包含的物品)放入一个空白列表,该列表将保留该用户的库存:

user_inventory = []

谁能告诉我该怎么做?

您应该使用字典,其中的键是您希望用户输入的输入

items = {"1":[1,2,3,4],"2":[2,3,4,5]}
user_inventory = []
while True:
   item = raw_input("Which Item would you like?")
   if item == "" or item.lower() == "q" or item.lower() == "quit":
       #user is done entering items
       break
   if item in items:
       #this is a little dicey since it is actually the same list, not a copy of the list
       user_inventory.append(items[item]) #you may want to insert a copy of the list instead
   else:
       print "Unknown Item:%s"%item

暂无
暂无

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

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