2015-04-28 21 views
0

我非常擅長python,不知道如何正確地問這個問題,所以在這裏。如何查找列表中的特定項目並使用該項目執行操作

我想獲得用戶輸入,並使用它來查找列表中的項目,然後讓該項目做一些事情......我不知道該怎麼做。

排序是這樣的:

things = ['thing1','thing2','thing3'] 
item = input('type your item here') 
if item in things == True: 
    if item == 'thing1': 
     do something 
    elif item == 'thing2': 
     do something else 
    elif item == 'thing 3': 
     do something different 

什麼想法?

感謝

+4

你真的**試過**你的代碼嗎?如果是這樣,發生了什麼,以及這與你的期望有什麼不同?如果沒有,爲什麼不呢?! – jonrsharpe

+0

您錯過了'elif item =='的結束語[3]:應該是elif item =='thing 3': –

+0

我不知道這是否會回答您的問題,但您的問題存在一個錯誤防止所有其他if語句被執行的代碼。看看第三行'if item in things == True:'它應該是'if things in things:' – kstenger

回答

1

使用字典,用字符串作爲鍵,功能價值:

todos = { 
    'thing1': do_something, 
    'thing2': do_something_else, 
    'thing3': do_something_different, 
} 

item = input('type your item here') 
todos.get(item, lambda: None)() 
0

我個人認爲你應該使用一個過濾器,僅提取了該項目的數組你想「做什麼」數組,那麼每個元素的新陣列

//in this example I use filter to select all the even numbers in the 
 
//list and compute their square 
 

 
//here is a list of numbers 
 
array = [1,2,4,5,7] 
 

 
//use a filter to take only the elements from the list you need 
 
//the elements part of the new array, arrEvens, will be all the 
 
//elements of array that return true in the lambda expression 
 
arrEvens = filter(lambda a : a%2 ==0, array) 
 

 
//do something (in this case print the square) of all the 
 
//numbers in the new list of elements that passed the filtering 
 
//test 
 
for x in arrEvens: 
 
    print(x*x)
在使用,爲表達「做什麼」

希望我正確理解你的問題,這有助於。

+0

我沒有想過使用過濾器,它可以工作,如果我瞭解如何正確使用它。就我而言,它可能不是最好的選擇,我只想在我的列表中選擇一個項目,這是用戶輸入的任何內容,並讓該項目執行某些操作。感謝你的回答! –

+0

hmm是否必須從數組中挑選值?當用戶輸入數據並分別更新數組時,您可以簡單地使用該值嗎? – jmdevivo

+0

這是一個非常好的觀點,我想如果我想在稍後添加更多選項,它會更容易更新,但經過反思,我不認爲這會是......嗯,至少我學到了一些新東西!謝謝 –

0

丹尼爾說正確的,要使用字典待辦事項, 很好的情況下,如果有要執行的匹配功能 你可以試試這個:

todos = { 'thing1': function1, 
      'thing2': function2, 
      'thing3': function3 } 
def function1(): 
    """any operation """ 
    pass 
def function2(): 
    """any operation """ 
    pass 
def function3(): 
    """ any operation """ 
    pass 

input_val = raw_input("Enter the thing to do") 
todos[input_val]() 

希望它能幫助,

+0

我完全沒有意識到你可以把函數放在字典中。我想這會解決我的問題,謝謝Daniel和爵士, –

相關問題