lambda表達式,結合map、reduce、filter函數

lambda函數是一種快速定義單行最小函數的方法,是從Lisp借鑑而來的,可以用在任何需要函數的地方。

基礎

lambda語句中,冒號前是參數,可以有多個,用逗號分割;冒號右邊是返回值。
lambda語句構建的是一個函數對象。

# 兩個參數,x和y,返回兩個參數的和
>>> f = lambda x, y: x+y
>>> type(f)
<type 'function'>
>>> f
<function <lambda> at 0x7f6d023000c8>
>>> f(10, 12)
22
>>> f("hello ", "world")
'hello world'

map

map(…) 函數官方文檔
map函數結果生成一個list,參數爲函數、一個或多個序列;如果函數的參數只有一個,那麼應該有一個序列,有多個參數,那麼應該有相應數量的序列。
簡單的說:map(function,sequence) :對sequence中的item依次執行function(item),見執行結果組成一個List返回
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).

>>> map(lambda x: x*2, range(1,10))
[2, 4, 6, 8, 10, 12, 14, 16, 18]
>>> map(lambda x, y: x*y, range(1,10), range(2, 11))
[2, 6, 12, 20, 30, 42, 56, 72, 90]
>>> map(lambda x: 1, range(1,10))
[1, 1, 1, 1, 1, 1, 1, 1, 1]

官方文檔中最後一句解釋,特別重要: map函數的參數中有一個是function(函數),這個函數也可以是None(那句話的意思不是返回值是None)。如果是None的話,map就與zip函數類似了,看下面的例子, 區別已經在zip函數介紹過了。

>>> map(None, range(10), range(1, 11))
[(0, 1), (1, 2), (2, 3), (3, 4), (4, 5), (5, 6), (6, 7), (7, 8), (8, 9), (9, 10)]
>>> zip(range(10), range(1, 11))
[(0, 1), (1, 2), (2, 3), (3, 4), (4, 5), (5, 6), (6, 7), (7, 8), (8, 9), (9, 10)]
>>> zip(range(10))
[(0,), (1,), (2,), (3,), (4,), (5,), (6,), (7,), (8,), (9,)]
>>> map(None, range(10))
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

因此,map函數的執行過程,……不好描述啊……

reduce

reduce(function,sequence):對sequence中的item順序迭代調用function。
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.
根據文檔裏面顯示的代碼:

>>> reduce(lambda x, y: x+y, [1, 2, 3, 4, 5])
15
# 內部執行過程,((((1+2)+3)+4)+5)

# list只有一個元素
>>> reduce(lambda x: x+2, [1])
1

#reduce 如果list的長度大於1,lambda表達式必須有兩個參數(大於2個參數是不對的)
>>> reduce(lambda x: x+2, [1, 2, 3, 4, 5])
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: <lambda>() takes exactly 1 argument (2 given)

filter

filter(function,sequence):對sequence中的item依次執行function(item),將執行結果爲True的item組成一個List/String/Tuple(取決於sequence的類型)返回。

>>> filter(lambda x:x>10, range(1,20))
[11, 12, 13, 14, 15, 16, 17, 18, 19]

>>> filter(lambda s: s != 'a' , 'abcdefg')
'bcdefg'
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章