2015-10-18 41 views
2

我試圖通過將它們映射到我的查找表中的鍵來運行一些函數。我有一個列表lis,我遍歷它並檢查列表中的某些值是否與查找表中的鍵相同。如果他們是我想按照關鍵運行功能。 當我嘗試運行下面的代碼時,它會將它們全部打印出來3,我不明白。Python,從查找表運行函數

因爲它應該只在我眼中打印1和2。

ops1 = { 


     "1": print("1"), 
     "2": print("2"), 
     "4": print("4") 
} 

lis = [1, 2, 3] 

for x in range(0, len(lis)-1): 
    if (lis[x] in ops1.keys()): 
     ops1.get(x) 
+3

你知道'print(x)'是做什麼的嗎? –

+1

你確定這是你正在運行的確切代碼嗎?因爲它不是有效的Python語法。 –

+0

我也不明白你在做什麼循環。你創建一個只包含0和1的範圍,然後將它連接到一個單獨的'list'的索引,然後將它連接到字典。 – TigerhawkT3

回答

2

讓我們一行一行地看看它。

ops1 = { 
     "1": print("1"), # this value is actually the value returned by print 
     "2": print("2"), 
     "4": print("4") 
} # when the dictionary is created, everything in it is evaluated, 
# so it executes those print calls 
# that's why you see all three printed 

lis = [1, 2, 3] 

for x in range(0, len(lis)-1): # this includes 0 and 1 
    if (lis[x] in ops1.keys()): # lis[0] is 1 and lis[1] is 2 
     ops1.get(x) # look for 0 and then 1 in the dictionary 

現在讓我們來修復它。

ops1 = { 
     "1": lambda: print("1"), # this value is now a FUNCTION, which you can call later 
     "2": lambda: print("2"), 
     "4": lambda: print("4") 
} # when the dictionary is created, everything in it is evaluated, but the functions are not called 

lis = [1, 2, 3] 

for x in range(len(lis)): # goes through 0, 1, and 2 
    if lis[x] in ops1: # lis[0] is 1, lis[1] is 2, lis[2] is 3 
     ops1.get(str(lis[x]), print)() # look for '1', '2', and '3', 
             # then call their values 

你可以改善,去年環這樣的:

for x in lis: 
    ops1.get(str(x), print)() 

所以,首先我們來看看了關鍵'1'。這對應於一個函數。然後我們調用這個函數。這會打印字符串'1\n'。然後我們查找關鍵字'2'。這對應於一個函數。然後我們調用這個函數。這會打印字符串'2\n'。然後我們查找關鍵字'3'。這在字典中不存在,所以它返回一個默認函數。然後我們稱之爲默認功能。這會打印字符串'\n'

+0

非常感謝您的明確解釋!非常感激。我現在有一些工作,謝謝! – JonCode

1

試試這個(大約)

問題是你要分配的結果調用打印即無,你的查找表的。您想分配功能定義而不是,wo調用它。然後在循環中調用查找函數。

def print1(): 
    print(1) 

Ops = { 
"1" : print1, 
"2" : another_func, 
... 

} 

for key in ["1","2","3"]: 
    ops[key]()