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

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

    If you still want to print you can import future module

    from __future__ import print_function
    
    f = lambda x: print(x) if x%2 == 0 else False
    
    0 讨论(0)
  • 2020-12-12 09:20

    Hope this will help a little

    you can resolve this problem in the following way

    f = lambda x:  x==2   
    
    if f(3):
      print("do logic")
    else:
      print("another logic")
    
    0 讨论(0)
  • 2020-12-12 09:21

    Try it:

    is_even = lambda x: True if x % 2 == 0 else False
    print(is_even(10))
    print(is_even(11))
    

    Out:

    True
    False
    
    0 讨论(0)
  • 2020-12-12 09:22

    Following sample code works for me. Not sure if it directly relates to this question, but hope it helps in some other cases.

    a = ''.join(map(lambda x: str(x*2) if x%2==0 else "", range(10)))
    
    0 讨论(0)
  • 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
    
    0 讨论(0)
  • 2020-12-12 09:24

    I think this is what you were looking for

    >>> f = lambda x : print(x) if x==2 else print("ERROR")
    >>> f(23)
    ERROR
    >>> f(2)
    2
    >>> 
    
    0 讨论(0)
提交回复
热议问题