Python lambda with if but without else

前端 未结 4 1225
长发绾君心
长发绾君心 2021-01-30 20:49

I was writing some lambda functions and couldn\'t figure this out. Is there a way to have something like lambda x: x if (x<3) in python? As lambda a,b: a i

4条回答
  •  被撕碎了的回忆
    2021-01-30 21:39

    A lambda, like any function, must have a return value.

    lambda x: x if (x<3) does not work because it does not specify what to return if not x<3. By default functions return None, so you could do

    lambda x: x if (x<3) else None
    

    But perhaps what you are looking for is a list comprehension with an if condition. For example:

    In [21]: data = [1, 2, 5, 10, -1]
    
    In [22]: [x for x in data if x < 3]
    Out[22]: [1, 2, -1]
    

提交回复
热议问题