【发布时间】:2015-06-08 15:05:46
【问题描述】:
我知道您可以使用字典来替代 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]
但是,如果使用条件,除了返回 true 或 false 的等式 (==) 之外,这些不能很容易地映射,即:
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" }
可以使用 lambda,因为它是可散列的,但从映射中获取结果字符串的唯一方法是将相同的 lambda 对象传递到字典中,而不是在 lambda 的评估为真时:
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 评估和返回值之间创建映射的技术或方法吗? (这可能类似于函数式语言中的模式匹配)
【问题讨论】:
-
“但显然它只有在 lambda 本身被传递时才有可能,而不是当 lambda 的评估为真时” 抱歉,您能改写一下吗?我不明白你的意思。
-
@Kevin 好的,我刚刚编辑了答案以澄清这一点
标签: python python-2.7 dictionary lambda