Python lambda with if but without else

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

    You can always try to invoke 'filter' for conditional checks. Fundamentally, map() has to work on every occurrence of the iterables, so it cannot pick and choose. But filter may help narrow down the choices. For example, I create a list from 1 to 19 but want to create a tuple of squares of only even numbers.

    x = list(range(1,20))
    
    y = tuple(map(lambda n: n**2, filter(lambda n: n%2==0,x)))
    
    print (y)
    

提交回复
热议问题