讓我們一行一行地看看它。
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'
。
你知道'print(x)'是做什麼的嗎? –
你確定這是你正在運行的確切代碼嗎?因爲它不是有效的Python語法。 –
我也不明白你在做什麼循環。你創建一個只包含0和1的範圍,然後將它連接到一個單獨的'list'的索引,然後將它連接到字典。 – TigerhawkT3