我知道你可以使用字典來替代switch語句,如以下幾點:如何將一系列條件映射爲字典中的鍵?
def printMessage(mystring):
# Switch statement without a dictionary
if mystring == "helloworld":
print "say hello"
elif mystring == "byeworld":
print "say bye"
elif mystring == "goodafternoonworld":
print "good afternoon"
def printMessage(mystring):
# Dictionary equivalent of a switch statement
myDictionary = {"helloworld": "say hello",
"byeworld": "say bye",
"goodafternoonworld": "good afternoon"}
print myDictionary[mystring]
但是如果使用條件下,比返回的錯誤,這些不能被映射真正的平等(==)等作爲容易即:
if i > 0.5:
print "greater than 0.5"
elif i == 5:
print "it is equal to 5"
elif i > 5 and i < 6:
print "somewhere between 5 and 6"
上面不能直接轉換爲一個字典鍵 - 值對作爲是:
# this does not work
mydictionary = { i > 0.5: "greater than 0.5" }
甲羊肉DA可以使用,因爲它是散列能,但通過將相同的拉姆達對象到詞典中,而不是當拉姆達的評價是真實的,以獲得結果字符串出地圖的唯一方法:
x = lambda i: i > 0.5
mydictionary[x] = "greater than 0.5"
# you can get the string by doing this:
mydictionary[x]
# which doesnt result in the evaluation of x
# however a lambda is a hashable item in a dictionary
mydictionary = {lambda i: i > 0.5: "greater than 0.5"}
有誰知道在lambda評估和返回值之間創建映射的技術或方法嗎? (這可能類似於功能語言中的模式匹配)
_「但顯然其唯一可能的情況下本身是由過去了,拉姆達不能當拉姆達的評價是真實的」 _對不起,你能換一種說法?我不明白你的意思。 – Kevin 2015-04-03 14:05:02
@凱文好吧我剛剛編輯了答案,以澄清這一點 – Har 2015-04-03 14:33:11