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

后端 未结 16 1982
长发绾君心
长发绾君心 2020-12-12 08: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
<         


        
相关标签:
16条回答
  • 2020-12-12 09:26

    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
    
    0 讨论(0)
  • 2020-12-12 09:28

    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.

    0 讨论(0)
  • 2020-12-12 09:28

    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.

    0 讨论(0)
  • 2020-12-12 09:28

    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
    
    0 讨论(0)
  • 2020-12-12 09:32

    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.

    0 讨论(0)
  • 2020-12-12 09:33

    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)
    
    0 讨论(0)
提交回复
热议问题