Lambda代替“if”陈述
我听说可以使用 lambda 来替换 if
语句。
这在Python中可能吗?如果是这样,怎么办?
I've heard that it is possible to substitute an if
statement by using a lambda.
Is this possible in Python? If so, how?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
也许您指的是这样的东西(Lambda calculus)?
你可以使用它......
但现在事情开始崩溃......
所以,不那么漂亮,或有用。但它有效。
Perhaps you are referring to something like this (Lambda calculus)?
Which you could use like...
But now things start to fall apart...
So, not so pretty, or useful. But it works.
和其他人一样,我不确定你在问什么,但我愿意猜测。
我有时会以一种有点古怪的方式使用 lambda 来处理 API 调用的结果。
例如,API 调用结果的一个元素应该是一个数字字符串,我希望它作为整数,但有时它会返回其他内容。
您可以定义一个 lambda 将由数字组成的字符串转换为整数:
这避免了
if
语句,但不是因为lambda
,您可以这样做与函数相同:更新
更少的错误黑客,由 Paul McGuire 提供:
ie as
int('0')
返回相当于False< /code> lambda 的返回可能会让你大吃一惊当您想要
0
时,
无
Like the others, I'm not sure what you're asking about, but I'm willing to have a guess.
I sometimes use lambdas in a bit of a hacky way processing results from API calls.
Say for example an element of an API call result should be a numeric string which I'd want as an integer, but occasionally it returns something else.
You could defined a lambda to turn a string into an integer if it is comprised of digits:
This is avoiding an
if
statement, but not because of thelambda
, you could do the same as a function:Update
Less buggy hack, courtesy of Paul McGuire:
i.e. as
int('0')
returns an equivalent ofFalse
the lambda might surprise you by returningNone
when you wanted0
我可能会严重偏离,但我想这意味着类似:
会返回
list_of_values
中值大于 0 的元素。I might be seriously off, but I'd imagine this means something like:
Would return you the elements from
list_of_values
which have a value greater than 0.以下是受 Smalltalk 启发的一个小技巧
语言核心,不使用 if 语句或三元
运算符,但作为条件执行
机制。 :-)
更新:整理一些符号以避免混淆并使要点清晰。并添加了代码来展示如何实现逻辑运算符的快捷计算。
Following is a little trick inspired by Smalltalk
language core, which does not use if statement nor ternary
operator, yet working as a conditional execution
mechanism. :-)
UPDATE: Tidy up some symbols to avoid confusion and make the point clear. And added code to show how short-cut evaluation of logical operators can be implemented.
是
但尚不清楚您在寻找什么。
请注意,这不是一个
if
语句 - 它是一个 三元运算。在 Python 中,它们都使用单词if
。有关 C# 中的示例,请参阅 Lambda“if”语句?。is
But it's not clear what you're looking for.
Note that this is not an
if
statement -- it's a ternary operation. In Python, they just both use the wordif
. See for example Lambda "if" statement? for this in C#.