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

后端 未结 16 2103
长发绾君心
长发绾君心 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: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)
    

提交回复
热议问题