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

后端 未结 16 2152
长发绾君心
长发绾君心 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条回答
  •  猫巷女王i
    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.

提交回复
热议问题