问题:有没有办法在python的lambda中执行“如果”

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

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

谢谢

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?

thanks


回答 0

您要寻找的语法:

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

但是您不能使用printraise使用lambda。

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.


回答 1

为什么不只是定义一个函数?

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.


回答 2

到目前为止,我可能写的最糟糕的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.


回答 3

如果您确实要这样做,则可以在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.


回答 4

就允许使用的内容而言,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

回答 5

请注意,您可以在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

回答 6

如果仍要打印,则可以导入以后的模块

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

回答 7

您还可以使用逻辑运算符来进行类似条件运算的操作

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


回答 8

您真正需要的是

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)

回答 9

此代码段应帮助您:

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

回答 10

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

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

回答 11

尝试一下:

is_even = lambda x: True if x % 2 == 0 else False
print(is_even(10))
print(is_even(11))

出:

True
False

Try it:

is_even = lambda x: True if x % 2 == 0 else False
print(is_even(10))
print(is_even(11))

Out:

True
False

回答 12

在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

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。