lambda 中的布尔计算
只是为了我自己的娱乐而使用工具,我想使用 lambda,因为我喜欢它。 我可以用 lambda 替换这个函数吗?
def isodd(number):
if (number%2 == 0):
return False
else:
return True
初级,是的。 但我有兴趣知道...
Just tooling around for my own amusement, and I want to use a lambda, because I feel like it. Can I replace this function with a lambda?
def isodd(number):
if (number%2 == 0):
return False
else:
return True
Elementary, yes. But I'm interested to know...
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(8)
如果您确实不需要某个函数,即使没有 lambda,您也可以替换它。 :)
本身就是一个计算结果为 True 或 False 的表达式。 或者甚至更简单,
您可以像这样简化:
但是否可读可能取决于情人的眼睛。
And if you don't really need a function you can replace it even without a lambda. :)
by itself is an expression that evaluates to True or False. Or even plainer,
which you can simplify like so:
But if that's readable or not is probably in the eye of the beholder.
是的你可以:
Yes you can:
其他人已经给了您涵盖您的具体情况的答复。 不过,一般来说,当您确实需要 if 语句时,可以使用条件表达式。 例如,如果您必须返回字符串
"False"
和"True"
而不是布尔值,您可以这样做:Python 语言参考中该表达式的定义如下:
Others already gave you replies that cover your particular case. In general, however, when you actually need an
if
-statement, you can use the conditional expression. For example, if you'd have to return strings"False"
and"True"
rather than boolean values, you could do this:The definition of this expression in Python language reference is as follows:
并且不要忘记,您可以使用简单的短路逻辑来模拟复杂的条件句子,利用“and”和“or”返回它们的一些元素(最后一个评估的元素)......例如,在本例中,假设您想要返回与 True 或 False 不同的内容
And also don't forget that you can emulate complex conditional sentences with simple short-circuit logic, taking advantage that "and" and "or" return some of their ellements (the last one evaluated)... for example, in this case, supposing you'd want to return something different than True or False
isodd = lambda 数:(False, True)[number & 1]
isodd = lambda number: (False, True)[number & 1]
任何时候你看到自己写:
你应该用一行替换它:
你的函数然后变成:
你应该能够看到如何从那里到达其他人提供的 lambda 解决方案。
Any time you see yourself writing:
you should replace it with a single line:
Your function then becomes:
You should be able to see how to get from there to the lambda solution that others have provided.