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

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

    This snippet should help you:

    x = lambda age: 'Older' if age > 30 else 'Younger'
    
    print(x(40))
    
    0 讨论(0)
  • 2020-12-12 09:34

    You can also use Logical Operators to have something like a Conditional

    func = lambda element: (expression and DoSomething) or DoSomethingIfExpressionIsFalse
    

    You can see more about Logical Operators here

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

    The syntax you're looking for:

    lambda x: True if x % 2 == 0 else False
    

    But you can't use print or raise in a lambda.

    0 讨论(0)
提交回复
热议问题