Python的条件表达式和lambda表达式

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/chuan_day/article/details/76685996

Python的条件表达式和lambda表达式


  • 条件表达式
  条件表达式也称为三元表达式,表达式的形式:x if C else y。 流程是:如果C为真,那么执行x,否则执行y。
  经过测试x,y,C可以是函数,表达式,常量等等;
   
def put():
    print('this is put()')

def get():
    print('this is get()')

def post():
    return 0

method = put if post() else get
method()  
  •   lambda表达式
   lambda [arguments] : expression用来创建匿名函数
  
method = lambda x : x**2
ret = method(2)
print(ret)

  不同使用场景:
  
#if语句中f(1)==1时,前面的两个lambda表达式结果为1时,就返回,然后存于list中
f = [f for f in (lambda x: x, lambda x: x ** 2) if f(1) == 1]
print(f)#[<function <lambda> at 0x035B2930>, <function <lambda> at 0x035B2858>]
print(f[0](2))#返回:2
print(f[1](2))#返回:4
 放于函数中:
def action(x):
     return lambda y:x+y
f = action(2)
f(22) #24
#也可以直接:
action(2)(22)#返回:24


   
  



猜你喜欢

转载自blog.csdn.net/chuan_day/article/details/76685996