(1)lambda
lambda是Python中一個很有用的語法,它允許你快速定義單行最小函數。類似于C語言中的宏,可以用在任何需要函數的地方。
基本語法如下:
函數名 = lambda args1,args2,...,argsn : expression
例如:
1
2
|
add = lambda x,y : x + y print add( 1 , 2 ) |
(2)filter
filter函數相當于一個過濾器,函數原型為:filter(function,sequence),表示對sequence序列中的每一個元素依次執行function,這里function是一個bool函數,舉例說明:
1
2
3
4
|
sequence = [ 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 , 10 ] fun = lambda x : x % 2 = = 0 seq = filter (fun,sequence) print seq |
以下代碼就是表示篩選出sequence中的所有偶數。
filter函數原型大致如下:
1
2
3
4
5
6
|
def filter (fun,seq): filter_seq = [] for item in seq: if fun(item): filter_seq.append(item) return filter_seq |
(3)map
map的基本形式為:map(function,sequence),是將function這個函數作用于sequence序列,然后返回一個最終結果序列。比如:
1
2
3
4
|
seq = [ 1 , 2 , 3 , 4 , 5 , 6 ] fun = lambda x : x << 2 print map (fun,seq) |
map的函數源代碼大致如下:
1
2
3
4
5
|
def map (fun,seq): mapped_seq = [] for item in seq: mapped_seq.append(fun(item)) return mapped_seq |
(4)reduce
reduce函數的形式為:reduce(function,sequence,initVal),function表示一個二元函數,sequence表示要處理的序列,而initVal表示處理的初始值。比如:
1
2
3
4
|
seq = [ 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 , 10 ] fun = lambda x,y: x + y print reduce (fun,seq, 0 ) |
表示從初始值0開始對序列seq中的每一個元素累加,所以得到結果是55
reduce函數的源代碼大致如下:
1
2
3
4
5
6
7
8
9
|
def reduce (fun,seq,initVal = None ): Lseq = list (seq) if initVal is None : res = Lseq.pop( 0 ) else : res = initVal for item in Lseq: res = fun(seq,item) return res |
(5)apply
apply是用來間接地代替某個函數,比如:
1
2
3
4
|
def say(a,b): print a,b apply (say,( 234 , 'Hello World!' )) |