2015-06-11 39 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) 

現在你可以在給定的索引打印的項目