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

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

    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
    

提交回复
热议问题