据说是函数式编程的一个函数(然后也有人tucao py不太适合干这个),在我看来算是pythonic的一种写法。
简化了我们的操作,比方我们想将list中的数字都加1,最基本的可能是编写一个函数:
In [40]: def add_one(i): ....: return i+1 ....: In [41]: for i in range(1, 3): ....: print add_one(i) ....: 2 3
如果使用map就简单一些了:
In [42]: map(add_one, range(1, 3)) Out[42]: [2, 3]
其实这里还不够pythonic, 毕竟我们忘记了还有lambda这个匿名函数
In [44]: map(lambda x: x+1, range(1, 3)) Out[44]: [2, 3]
reduce的作用是对可迭代对象依次做某种操作,比方说依次相加或者乘之类的
内置的说明如下:
Help on built-in function reduce in module __builtin__: 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. (END)
使用方法如下:
In [18]: reduce(lambda x, y: x*y, [1, 2, 3]) Out[18]: 6
In [19]: reduce(lambda x, y: x*y, [1]) Out[19]: 1 In [20]: reduce(lambda x, y: x*y, [], 0) # 最后一个为初始值 Out[20]: 0
filter是对可迭代对象做某种过滤,使用方法和上面两个相似:
Help on built-in function filter in module __builtin__: 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.
In [22]: filter(lambda x: x > 5, range(10)) Out[22]: [6, 7, 8, 9]
基本使用方法大致如上,可能觉得刚开始觉得用处不大,实际上用习惯了就会觉得十分顺手
比方说让大家求1到100的和,可能函数写出来也只有几行代码,但是你用reduce呢,就只有一行。
大家可以试着用这种方法算一下 1!+2!+...+100!
(发现内置的文档已经很赞了~
参考见:
http://my.oschina.net/zyzzy/blog/115096
https://eastlakeside.gitbooks.io/interpy-zh/content/Map%20&%20Filter/index.html