1. 程式人生 > >Python中特殊函數和表達式 filter,map,reduce,lambda

Python中特殊函數和表達式 filter,map,reduce,lambda

result before positive ply sequence items closed 默認 hid

1. filter

官方解釋:filter(function or None, sequence) -> list, tuple, or string

Return those items of sequence for which function(item) is true. If function is None, return the items that are true. If sequence is a tuple or string, return the same type, else return a list.

傳入參數:function或None,序列

功能:將按照function中定義的方式進行過濾,返回True的留下,返回False的剔除。

技術分享圖片
1 #coding=utf-8
2 def findPositiveNum(num):
3     if num > 0:
4         return True
5     else:
6         return False
7     
8 list={2,1,3,-2,0,12,5,-9}
9 print filter(findPositiveNum,list)
View Code

返回結果:

[1, 2, 3, 5, 12]

  

2. map

官方解釋:

map(function, sequence[, sequence, ...]) -> list Return a list of the results of applying the function to the items of the argument sequence(s). If more than one sequence is given, the function is called with an argument list consisting of the corresponding item of each sequence, substituting None for missing values when not all sequences have the same length. If the function is None, return a list of the items of the sequence (or a list of tuples if more than one sequence).

傳入參數:function或None,序列

功能:將序列的中的各個參數傳入function中作為參數執行,返回的結果就是序列的值傳入function中執行的結果,是一個序列。如果function為None,那麽返回值為序列本身。

技術分享圖片
1 def multiValue(num):
2     return num**2
3 
4 list1={1,3,5,7,9,11}
5 print map(multiValue,list1)
View Code

返回結果:

[1, 9, 25, 49, 81, 121]

如果function傳入為None則返回值為

[1, 3, 5, 7, 9, 11]

3. reduce

官方解釋:

reduce(function, sequence[, initial]) -> value

Apply a function of two arguments cumulatively to the items of a sequence,from left to right, so as to reduce the sequence to a single value.For example, reduce(lambda x, y: x+y, [1, 2, 3, 4, 5]) calculates((((1+2)+3)+4)+5). If initial is present, it is placed before the items of the sequence in the calculation, and serves as a default when the sequence is empty.

將兩個參數的函數累積到序列項上,從左到右,以將序列減少到單個的子序列示例中,減少(λx,y:x+y,[1,2,3,4,5])計算(1+2)+3)+4)。如果初始存在,則將其放在計算序列項之前,當序列為空時作為默認值。

1 def addNum(num1,num2):
2     return num1+num2
3 
4 list2={1,2,3,4,5,6}
5 print reduce(addNum, list2)

代碼解釋:先計算1+2的值,然後將計算的值作為第一個參數傳入addNum中,第二個參數為3,依次類推。 最終結果為:

21

如果傳入初始值得話則:

1 def addNum(num1,num2):
2     return num1+num2
3 
4 list2={1,2,3,4,5,6}
5 #print reduce(addNum, list2)
6 print reduce(addNum, list2,100)

結果為:

121

4. lambda 可以用來定義匿名函數

1 addnum= lambda x,y:x+y
2 print addnum(1,2)
3 multiNum=lambda x:x**2
4 print multiNum(5)

結果為

3
25

Python中特殊函數和表達式 filter,map,reduce,lambda