简体   繁体   English

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

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

I am new to programming and am trying to update a pre-established list based upon user input in Python 2.5. 我是编程新手,正在尝试根据Python 2.5中的用户输入更新预先建立的列表。

Here is exactly what I am trying to do: 这正是我想做的事情:

I have various items that a user must choose from...let's use the following as an example: 我有用户必须选择的各种项目...让我们以以下示例为例:

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

I have the user choosing which item by using raw_input: 我让用户通过使用raw_input选择哪个项目:

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

Once they have chosen their appropriate item, I want to place the appropriate item (along with the items contained in that respective list) into a blank list that will maintain that user's inventory: 一旦他们选择了合适的物品,我想将相应的物品(以及相应列表中包含的物品)放入一个空白列表,该列表将保留该用户的库存:

user_inventory = []

Can anyone show me how to do this? 谁能告诉我该怎么做?

you should use a dictionary where the keys are the input you expect the user to enter 您应该使用字典,其中的键是您希望用户输入的输入

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