Is there a way to perform “if” in python's lam

2019-01-29 14:38发布

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

标签: python lambda
11条回答
The star\"
2楼-- · 2019-01-29 15:17

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
查看更多
Explosion°爆炸
3楼-- · 2019-01-29 15:21

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.

查看更多
SAY GOODBYE
4楼-- · 2019-01-29 15:23

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.

查看更多
相关推荐>>
5楼-- · 2019-01-29 15:29

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
查看更多
Bombasti
6楼-- · 2019-01-29 15:33

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

查看更多
贼婆χ
7楼-- · 2019-01-29 15:33

This snippet should help you:

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

print(x(40))
查看更多
登录 后发表回答