我听说可以if
使用 lambda 替换语句。
这在 Python 中可能吗?如果是这样,怎么做?
也许您指的是这样的东西(Lambda演算)?
If = lambda test, x, y: test(x, y)
True = lambda x, y: x
False = lambda x, y: y
您可以使用...
# 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"
但现在事情开始分崩离析……
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"
所以,不是那么漂亮或有用。但它有效。
和其他人一样,我不确定你在问什么,但我愿意猜测一下。
我有时会以一种有点怪异的方式使用 lambdas 来处理 API 调用的结果。
例如,API 调用结果的元素应该是一个数字字符串,我希望它是一个整数,但偶尔它会返回其他内容。
如果字符串由数字组成,您可以定义一个 lambda 以将其转换为整数:
lambda x: x and x.isdigit() and int(x) or None
这是避免if
声明,但不是因为lambda
,您可以像函数一样执行以下操作:
def f(x):
return x and x.isdigit() and int(x) or None
更新
少马车黑客,由 Paul McGuire 提供:
lambda x: int(x) if x and x.isdigit() else None
即作为int('0')
返回等效的 lambda 可能会在你想要False
的时候返回让你感到惊讶None
0
我可能是认真的,但我想这意味着:
filter(lambda x: x > 0, list_of_values)
将返回list_of_values
值大于 0 的元素。
以下是受 Smalltalk 语言核心启发的一个小技巧,它不使用 if 语句或三元运算符,而是作为条件执行机制工作。:-)
#!/usr/bin/env python
class ATrue:
def ifThen(self,iftrue): iftrue()
def ifThenElse(self,iftrue,iffalse): return iftrue()
def andThen(self,other): return other()
def orElse(self,other): return self
class AFalse:
def ifThen(self,iftrue): pass
def ifThenElse(self,iftrue,iffalse): return iffalse()
def andThen(self,other): return self
def orElse(self,other): return other()
def echo(x): print x
if __name__=='__main__':
T = ATrue()
F = AFalse()
x = T # True
y = T.andThen(lambda: F) # True and False
z = T.orElse(lambda: F) # True or False
x.ifThenElse( lambda: echo("x is True"), lambda: echo("x if False"))
y.ifThenElse( lambda: echo("y is True"), lambda: echo("y if False"))
z.ifThenElse( lambda: echo("z is True"), lambda: echo("z if False"))
更新:整理一些符号以避免混淆并明确要点。并添加了代码以显示如何实现逻辑运算符的快捷评估。
if condition:
do_stuff()
else:
dont()
是
(lambda x: do_stuff() if x else dont())(condition)
但目前尚不清楚您在寻找什么。
请注意,这不是一个if
语句——它是一个三元运算。在 Python 中,它们都只是使用这个词if
。参见例如Lambda “if” 语句?在 C# 中为此。