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

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

    An easy way to perform an if in lambda is by using list comprehension.

    You can't raise an exception in lambda, but this is a way in Python 3.x to do something close to your example:

    f = lambda x: print(x) if x==2 else print("exception")
    

    Another example:

    return 1 if M otherwise 0

    f = lambda x: 1 if x=="M" else 0
    

提交回复
热议问题