條件表達(dá)式也稱為三元表達(dá)式,表達(dá)式的形式:x if C else y。流程是:如果C為真,那么執(zhí)行x,否則執(zhí)行y。
經(jīng)過測試x,y,C可以是函數(shù),表達(dá)式,常量等等;
1
2
3
4
5
6
7
8
9
10
11
|
def put(): print ( 'this is put()' ) def get(): print ( 'this is get()' ) def post(): return 0 method = put if post() else get method() |
1
2
3
4
5
|
lambda [arguments] : expression用來創(chuàng)建匿名函數(shù) method = lambda x : x * * 2 ret = method( 2 ) print (ret) |
不同使用場景:
1
2
3
4
5
|
#if語句中f(1)==1時,前面的兩個lambda表達(dá)式結(jié)果為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 |
放于函數(shù)中:
1
2
3
4
5
6
|
def action(x): return lambda y:x + y f = action( 2 ) f( 22 ) #24 #也可以直接: action( 2 )( 22 ) #返回:24 |
以上這篇Python的條件表達(dá)式和lambda表達(dá)式實例就是小編分享給大家的全部內(nèi)容了,希望能給大家一個參考,也希望大家多多支持服務(wù)器之家。
原文鏈接:https://blog.csdn.net/chuan_day/article/details/76685996