Python通过构建"lambda"提供一种在程序运行时创建一个匿名函数的机制,即,函数不是和一个函数名绑定的。Python中的lambda并不函数式编程中的lambda,但是却是一个很强大的用法,通常和``map(), filter(), reduce()``联合起来使用。
- 和普通函数的区别
```
>>> def f(x) : return x**2
...
>>> print f(8)
64
>>> g = lambda x: x**2
>>>
>>> print g(8)
64
```
- 注意到,lambda并未包含一个return的声明,同样,在任何一个需要函数的地方都可以使用lambda而不需要指代一个函数名。
-----------------------
##进阶用法
```
>>> 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)
139
```
P.S.
- map()用法
- map(function_to_apply, list_to_input)
- Most of the times we want to pass all the list elements to a function one-by-one and then collect the output.
- For Example
```
items = [1, 2, 3, 4, 5]
squared = []
for i in items:
squared.append(i**2)
```
这段的代码功能和下面的功能一样:
```
items = [1,2,3,4,5]
squared = list(map(lambda x: x**2, items))
```
- filter()用法
- filter creates a list of elements for which a function returns true.
- Reduce()用法
- reduce is a really usedful function for performing some computation on al list returning the result.
- It applies a rolling computation to sequential pairs of value.
- 下面的两个代码片段执行的功能是相等的:
```
product = 1
list = [1, 2, 3, 4]
for num in list:
product = product * num
# product = 24
```
```
from functools import reduce
product = reduce((lambda x, y: x * y), [1, 2, 3, 4])
```