I15*_*159 2 python lambda if-statement lambda-calculus
我听说可以if用lambda 替换一个语句.
这在Python中可行吗?如果是这样,怎么样?
也许你指的是这样的东西(Lambda演算)?
If = lambda test, x, y: test(x, y)
True = lambda x, y: x
False = lambda x, y: y
Run Code Online (Sandbox Code Playgroud)
哪个你可以用...
# I guess you have to convert them sometimes... oh well
C = lambda b: [False, True][b]
x = If(C(2 > 3), "Greater", "Less")
print(x)
# "Less"
Run Code Online (Sandbox Code Playgroud)
但现在事情开始分崩离析了......
If(C(2 > 3), print("Greater"), print("Less"))
# Invalid syntax unless you use
# from __future__ import print_function
# And if you do, it prints both!
# (Because python has eager evaluation)
# So we could do
True = lambda x, y: x()
False = lambda x, y: y()
# And then
If(C(2 > 3), lambda:print("Greater"), lambda:print("Less"))
# "Less"
Run Code Online (Sandbox Code Playgroud)
所以,不那么漂亮或有用.但它的确有效.
| 归档时间: |
|
| 查看次数: |
15601 次 |
| 最近记录: |