2015-06-11 42 views
0
list = [yes, no, seven] 

print ("What do you want to pull from the list?") 
answer = input() 

print (list[answer]) 

我该如何处理这种情况?我知道这个例子不起作用,但是如何让它起作用?从变量列表中调用东西

编辑:我宁愿它是数字I输入,0是,1表示没有发生; 2七,如果这是可能的

+0

[如何删除列表中的项目(如果它存在? (Python的)](http://stackoverflow.com/questions/4915920/how-to-delete-an-item-in-a-list-if-it-exists-python) –

回答

2

你正在寻找一个dict,而不是一个list

my_dictionary = {'yes':1, 'no':4, 'seven':9} 

answer = input("What do you want to pull from the dictionary? ") 

print(my_dictionary[answer]) 
0
list_ = [yes, no, seven] 

print ("What do you want to pull from the list?") 
answer = input() 

print (list_[list_.index(answer)]) 
0

首先,正确定义的项目清单:

>>> items = ['yes', 'no', 'seven'] 

注意,我把它称为items,因为list是一个内置的功能。

现在得到的输入:

>>> answer = input("What do you want to pull from the list? ") 

在这一点上,answer是一个字符串。但是,许多是需要在项目列表中的索引,所以它必须使用转换的内置int功能:

>>> print(items[index]) 

>>> index = int(answer) 

现在你可以在给定的索引打印的项目