Python lambda with if but without else

前端 未结 4 1218
长发绾君心
长发绾君心 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:26

    I found that filter provided exactly what I was looking for in python 2:

    >>> data = [1, 2, 5, 10, -1]
    >>> filter(lambda x: x < 3, data)
    [1, 2, -1]
    

    The implementation is different in 2.x and 3.x: while 2.x provides a list, 3.x provides an iterator. Using a list comprehension might make for a cleaner use in 3.x:

    >>> data = [1, 2, 5, 10, -1]
    >>> [filter(lambda x: x < 3, data)]
    [1, 2, -1]
    

提交回复
热议问题