Har*_*Har 13 python lambda dictionary python-2.7
我知道你可以使用字典作为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]
Run Code Online (Sandbox Code Playgroud)
但是,如果使用条件,除了返回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"
Run Code Online (Sandbox Code Playgroud)
以上内容不能直接转换为字典键值对:
# this does not work
mydictionary = { i > 0.5: "greater than 0.5" }
Run Code Online (Sandbox Code Playgroud)
可以使用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"}
Run Code Online (Sandbox Code Playgroud)
有没有人知道在lambda评估和返回值之间创建映射的技术或方法?(这可能类似于函数式语言中的模式匹配)
Mar*_*ers 16
你的条件是连续的; 你想一个接一个地测试,而不是在这里将少量键映射到一个值.改变条件的顺序可能会改变结果; 样本中的5结果值"greater than 0.5",而不是"it is equal to 5".
使用元组列表:
myconditions = [
(lambda i: i > 0.5, "greater than 0.5"),
(lambda i: i == 5, "it is equal to 5"),
(lambda i: i > 5 and i < 6, "somewhere between 5 and 6"),
]
Run Code Online (Sandbox Code Playgroud)
之后你可以依次访问每一个,直到匹配:
for test, message in myconditions:
if test(i):
return message
Run Code Online (Sandbox Code Playgroud)
重新排序测试将改变结果.
字典适用于您的第一个示例,因为存在针对由字典优化的多个静态值的简单相等性测试,但此处没有这样的简单等式.
| 归档时间: |
|
| 查看次数: |
910 次 |
| 最近记录: |