有没有办法执行“if”在 python 的 lambda 中?

发布于 2024-08-08 01:41:32 字数 247 浏览 3 评论 0原文

Python 2.6中,我想做:

f = lambda x: if x==2 print x else raise Exception()
f(2) #should print "2"
f(3) #should throw an exception

这显然不是语法。是否可以在 lambda 中执行 if ,如果可以,该怎么做?

In Python 2.6, I want to do:

f = lambda x: if x==2 print x else raise Exception()
f(2) #should print "2"
f(3) #should throw an exception

This clearly isn't the syntax. Is it possible to perform an if in lambda and if so how to do it?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

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

发布评论

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

评论(16

如梦 2024-08-15 01:41:32

您正在寻找的语法:

lambda x: True if x % 2 == 0 else False

但是您不能在 lambda 中使用 printraise

The syntax you're looking for:

lambda x: True if x % 2 == 0 else False

But you can't use print or raise in a lambda.

岁月如刀 2024-08-15 01:41:32

你为什么不直接定义一个函数呢?

def f(x):
    if x == 2:
        print(x)
    else:
        raise ValueError

在这种情况下确实没有理由使用 lambda。

why don't you just define a function?

def f(x):
    if x == 2:
        print(x)
    else:
        raise ValueError

there really is no justification to use lambda in this case.

裂开嘴轻声笑有多痛 2024-08-15 01:41:32

可能是我迄今为止写过的最糟糕的Python行:

f = lambda x: sys.stdout.write(["2\n",][2*(x==2)-2])

如果x == 2你打印,

如果x!= 2你提出。

Probably the worst python line I've written so far:

f = lambda x: sys.stdout.write(["2\n",][2*(x==2)-2])

If x == 2 you print,

if x != 2 you raise.

じ违心 2024-08-15 01:41:32

如果您确实想要这样做,您可以轻松地在 lambda 中引发异常。

def Raise(exception):
    raise exception
x = lambda y: 1 if y < 2 else Raise(ValueError("invalid value"))

这是个好主意吗?我的直觉一般是不要将错误报告放在 lambda 中;让它的值为 None 并在调用者中引发错误。不过,我不认为这本质上是邪恶的——我认为“y if x else z”语法本身更糟糕——只要确保你没有试图在 lambda 体中填充太多内容即可。

You can easily raise an exception in a lambda, if that's what you really want to do.

def Raise(exception):
    raise exception
x = lambda y: 1 if y < 2 else Raise(ValueError("invalid value"))

Is this a good idea? My instinct in general is to leave the error reporting out of lambdas; let it have a value of None and raise the error in the caller. I don't think this is inherently evil, though--I consider the "y if x else z" syntax itself worse--just make sure you're not trying to stuff too much into a lambda body.

薯片软お妹 2024-08-15 01:41:32

请注意,您可以在 lambda 定义中使用多个 else...if 语句:

f = lambda x: 1 if x>0 else 0 if x ==0 else -1

note you can use several else...if statements in your lambda definition:

f = lambda x: 1 if x>0 else 0 if x ==0 else -1
凯凯我们等你回来 2024-08-15 01:41:32

Python 中的 Lambda 对您可以使用的内容有相当的限制。具体来说,正文中不能包含任何关键字(andnotor 等运算符除外)。

所以,你不可能在你的例子中使用 lambda(因为你不能使用 raise),但如果你愿意承认这一点......你可以使用:

f = lambda x: x == 2 and x or None

Lambdas in Python are fairly restrictive with regard to what you're allowed to use. Specifically, you can't have any keywords (except for operators like and, not, or, etc) in their body.

So, there's no way you could use a lambda for your example (because you can't use raise), but if you're willing to concede on that… You could use:

f = lambda x: x == 2 and x or None
烟织青萝梦 2024-08-15 01:41:32

这段代码应该可以帮助你:

x = lambda age: 'Older' if age > 30 else 'Younger'

print(x(40))

This snippet should help you:

x = lambda age: 'Older' if age > 30 else 'Younger'

print(x(40))
沧笙踏歌 2024-08-15 01:41:32

如果您仍然想打印,可以导入未来的模块

from __future__ import print_function

f = lambda x: print(x) if x%2 == 0 else False

If you still want to print you can import future module

from __future__ import print_function

f = lambda x: print(x) if x%2 == 0 else False
东北女汉子 2024-08-15 01:41:32

您还可以使用逻辑运算符来获得类似条件的内容。

func = lambda element: (expression and DoSomething) or DoSomethingIfExpressionIsFalse

您可以在此处查看有关逻辑运算符的更多信息

You can also use Logical Operators to have something like a Conditional

func = lambda element: (expression and DoSomething) or DoSomethingIfExpressionIsFalse

You can see more about Logical Operators here

失与倦" 2024-08-15 01:41:32

给定场景的解决方案是:

f = lambda x : x if x == 2 else print("number is not 2")
f(30)  # number is not 2
f(2)   #2

the solution for the given scenerio is:

f = lambda x : x if x == 2 else print("number is not 2")
f(30)  # number is not 2
f(2)   #2
神也荒唐 2024-08-15 01:41:32

您现在真正需要的是

def fun():
    raise Exception()
f = lambda x:print x if x==2 else fun()

按照您需要的方式调用该函数

f(2)
f(3)

what you need exactly is

def fun():
    raise Exception()
f = lambda x:print x if x==2 else fun()

now call the function the way you need

f(2)
f(3)
旧街凉风 2024-08-15 01:41:32

在 lambda 中执行 if 的一种简单方法是使用列表理解。

您不能在 lambda 中引发异常,但这是 Python 3.x 中执行类似于您的示例的操作的一种方式:

f = lambda x: print(x) if x==2 else print("exception")

另一个示例:

如果 M 则返回 1,否则返回 0

f = lambda x: 1 if x=="M" else 0

An easy way to perform an if in lambda is by using list comprehension.

You can't raise an exception in lambda, but this is a way in Python 3.x to do something close to your example:

f = lambda x: print(x) if x==2 else print("exception")

Another example:

return 1 if M otherwise 0

f = lambda x: 1 if x=="M" else 0
软甜啾 2024-08-15 01:41:32

如果您使用 Python 3.x,这是解决方案!

>>> f = lambda x: print(x) if x == 2 else print("ERROR")
>>> f(23)
ERROR
>>> f(2)
2
>>> 

Here's the solution if you use Python 3.x!

>>> f = lambda x: print(x) if x == 2 else print("ERROR")
>>> f(23)
ERROR
>>> f(2)
2
>>> 
叹沉浮 2024-08-15 01:41:32

以下示例代码对我有用。不确定它是否与这个问题直接相关,但希望它在其他情况下有所帮助。

a = ''.join(map(lambda x: str(x*2) if x%2==0 else "", range(10)))

Following sample code works for me. Not sure if it directly relates to this question, but hope it helps in some other cases.

a = ''.join(map(lambda x: str(x*2) if x%2==0 else "", range(10)))
極樂鬼 2024-08-15 01:41:32

希望这对您有一点帮助,

您可以通过以下方式解决这个问题

f = lambda x:  x==2   

if f(3):
  print("do logic")
else:
  print("another logic")

Hope this will help a little

you can resolve this problem in the following way

f = lambda x:  x==2   

if f(3):
  print("do logic")
else:
  print("another logic")
ぺ禁宫浮华殁 2024-08-15 01:41:32

可能值得考虑 np.where

it might be worth considering np.where

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