Lambda代替“if”陈述

发布于 2024-11-29 12:55:24 字数 77 浏览 1 评论 0原文

我听说可以使用 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

执手闯天涯 2024-12-06 12:55:24

也许您指的是这样的东西(Lambda calculus)?

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"

所以,不那么漂亮,或有用。但它有效。

Perhaps you are referring to something like this (Lambda calculus)?

If = lambda test, x, y: test(x, y)
True = lambda x, y: x
False = lambda x, y: y

Which you could use like...

# 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"

But now things start to fall apart...

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"

So, not so pretty, or useful. But it works.

吲‖鸣 2024-12-06 12:55:24

和其他人一样,我不确定你在问什么,但我愿意猜测。

我有时会以一种有点古怪的方式使用 lambda 来处理 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

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:

lambda x: x and x.isdigit() and int(x) or None

This is avoiding an if statement, but not because of the lambda, you could do the same as a function:

def f(x):
  return x and x.isdigit() and int(x) or None

Update

Less buggy hack, courtesy of Paul McGuire:

lambda x: int(x) if x and x.isdigit() else None

i.e. as int('0') returns an equivalent of False the lambda might surprise you by returning None when you wanted 0

谈情不如逗狗 2024-12-06 12:55:24

我可能会严重偏离,但我想这意味着类似:

filter(lambda x: x > 0, list_of_values)

会返回 list_of_values 中值大于 0 的元素。

I might be seriously off, but I'd imagine this means something like:

filter(lambda x: x > 0, list_of_values)

Would return you the elements from list_of_values which have a value greater than 0.

何处潇湘 2024-12-06 12:55:24

以下是受 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"))

更新:整理一些符号以避免混淆并使要点清晰。并添加了代码来展示如何实现逻辑运算符的快捷计算。

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. :-)

#!/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"))

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.

苏别ゝ 2024-12-06 12:55:24
if condition:
    do_stuff()
else:
    dont()

(lambda x: do_stuff() if x else dont())(condition)

但尚不清楚您在寻找什么。

请注意,这不是一个 if 语句 - 它是一个 三元运算。在 Python 中,它们都使用单词 if。有关 C# 中的示例,请参阅 Lambda“if”语句?

if condition:
    do_stuff()
else:
    dont()

is

(lambda x: do_stuff() if x else dont())(condition)

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 word if. See for example Lambda "if" statement? for this in C#.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文