面向对象编程,我想大家都很清楚了.
函数式编程是将函数本身作为处理对象的编程范式.
最常用的就是lambda(匿名函数),有木有印象!!! 而且在定义一个lambda的时候,它返回的是一个函数类型
>>> a = lambda x: x + 1
>>> a
<function <lambda> at 0x7ffac88dc5f0>
还有一些常用的,如map,filter.举例使用
>>> 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]
itertools包含类似的工具。这些函数接收函数作为参数,并将结果返回为一个循环器
from itertools import *
rlt = imap(pow, [1, 2, 3], [1, 2, 3])
ifilter(lambda x: x > 5, [2, 3, 5, 6, 7]
chain([1, 2, 3], [4, 5, 7]) # 连接两个循环器成为一个。1, 2, 3, 4, 5, 7
product('abc', [1, 2]) # 多个循环器集合的笛卡尔积。相当于嵌套循环
>>> from itertools import *
>>> for m, n in product('abc', [1, 2]):
... print m, n
...
a 1
a 2
b 1
b 2
c 1
c 2
还有一些相同的用法,就到itertools里查看吧