條件表達式也稱為三元表達式,表達式的形式:x if C else y。流程是:如果C為真,那么執行x,否則執行y。
經過測試x,y,C可以是函數,表達式,常量等等;
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用來創建匿名函數 method = lambda x : x * * 2 ret = method( 2 ) print (ret) |
不同使用場景:
1
2
3
4
5
|
#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 |
放于函數中:
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的條件表達式和lambda表達式實例就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支持服務器之家。
原文鏈接:https://blog.csdn.net/chuan_day/article/details/76685996