Python: Lambda Functions

1. 做用

快速建立匿名單行最小函數,對數據進行簡單處理, 經常與 map(), reduce(), filter() 聯合使用。ide

2. 與通常函數的不一樣

>>> def f (x): return x**2
...
>>> print f(8)
64
>>>
>>> g = lambda x: x**2 # 匿名函數默認冒號前面爲參數(多個參數用逗號分開), return 冒號後面的表達式
>>>
>>> print g(8)
64

3. 與通常函數嵌套使用

與通常函數嵌套,能夠產生多個功能相似的的函數。函數

>>> def make_incrementor (n): return lambda x: x + n
>>>
>>> f = make_incrementor(2)
>>> g = make_incrementor(6)
>>>
>>> print f(42), g(42)
44 48
>>>
>>> print make_incrementor(22)(33)
55

4. 在 sequence 中的使用

filter(function or None, sequence) -> list, tuple, or stringspa

map(function, sequence[, sequence, ...]) -> listcode

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

>>> foo = [2, 18, 9, 22, 17, 24, 8, 12, 27]
>>>
>>> print filter(lambda x: x % 3 == 0, foo)
[18, 9, 24, 12, 27]
>>>
>>> print map(lambda x: x * 2 + 10, foo)
[14, 46, 28, 54, 44, 58, 26, 34, 64]
>>>
>>> print reduce(lambda x, y: x + y, foo) # return (((((a+b)+c)+d)+e)+f) equal to sum()
139

5. 兩個例子

a) 求素數element

>>> nums = range(2, 50)
>>> for i in range(2, 8):
... nums = filter(lambda x: x == i or x % i, nums)
...
>>> print nums
[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47]

註釋: "Leave the element in the list if it is equal to i, or if it leaves a non-zero remainder when divided by i. Otherwise remove it from the list." 從 2 到 7 循環,每次把倍數移除。rem

 

b) 求單詞長度get

>>> sentence = 'It is raining cats and dogs'
>>> words = sentence.split()
>>> print words
['It', 'is', 'raining', 'cats', 'and', 'dogs']
>>>
>>> lengths = map(lambda word: len(word), words)
>>> print lengths
[2, 2, 7, 4, 3, 4]

 

 



參考資料:string

http://www.secnetix.de/olli/Python/lambda_functions.hawkit

相關文章
相關標籤/搜索