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条回答
相关推荐>>
2楼-- · 2019-01-29 15:35

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)
查看更多
够拽才男人
3楼-- · 2019-01-29 15:36

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.

查看更多
Lonely孤独者°
4楼-- · 2019-01-29 15:38

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)))
查看更多
We Are One
5楼-- · 2019-01-29 15:41

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
查看更多
一纸荒年 Trace。
6楼-- · 2019-01-29 15:42

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.

查看更多
登录 后发表回答