本文主要是介绍The Python Tutorial学习笔记(2)--map、reduce、filter介绍,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
The Python Tutorial学习笔记(2)–map、reduce、filter介绍
filter
==filter(function, iterable)==
function表示返回布尔值的函数。如果function为空表示返回的布尔值为True,也就是没有过滤掉对象。
iterable可以是一个序列,一个容器支持迭代,迭代器 也就是说不仅仅适用于序列。``` def f(x): return x %3 == 0 or x%5 == 0filter(f, range(2, 25)) #output: #[3, 5, 6, 9, 10, 12, 15, 18, 20, 21, 24]>>> filter(None, range(2,5)) #output: #[2, 3, 4]
“`
map
==map(function, iterable, …)==
function 可以处理一个或者多个序列里边的位置相互对应的函数,
function 可以为空,具体体现在一下代码测试中:当function的参数只有一个时(对于不了lambda函数的文章末尾):
>>> map(lambda x:x*x, range(1,5))#output#[1, 4, 9, 16]#处理了range(1, 5)中的每一个元素>>> map(None, range(1,5))#output#[1, 2, 3, 4]#函数支持map 序列不发生变化#当函数只有一个参数时处理多个序列是则发生异常
当function的参数为两个时:
>>> map(None, range(1,5), range(1, 5))#output:#[(1, 1), (2, 2), (3, 3), (4, 4)]#返回值依次为序列但是序列元素为元祖,>>> map(lambda x,y: x*y, range(1,5), range(1, 5))#output#[1, 4, 9, 16]#按照匿名函数对两个序列位置对应的元素进行计算最后返回结果序列
当function的参数为两个以上是,依次类推。
reduce
==reduce(function, iterable[, initializer])==
function只有两个参数,也就是reduce以initializer为基准对序列元素进行累计运算。当initializer为None时却initializer为序列的第一个元素,如果元素不存在则抛出异常
``` >>> reduce(lambda x,y:x+y, range(1, 10))#output:45 >>> reduce(None, range(1, 10)) ...Traceback (most recent call last):File "<stdin>", line 1, in <module>File "<stdin>", line 10, in reduceTypeError: 'NoneType' object is not callable ... #语句报错```
附上reduce python实现
``` def reduce(function, iterable, initializer=None):it = iter(iterable)if initializer is None:try:initializer = next(it)except StopIteration:raise TypeError('reduce() of empty sequence with no initial value')accum_value = initializerfor x in it:accum_value = function(accum_value, x)return accum_value ```
lambda
lambda函数为匿名函数,python lambda它只是一个表达式,而def则是一个语句。lambda表达式运行起来像一个函数,当被调用时创建一个框架对象。具体详见:http://www.cnblogs.com/BeginMan/p/3178103.html
``` def add(x,y):return x+y add2 = lambda x,y:x+y print add2(1,2) #3def sum(x,y=10):return x+y sum2 = lambda x,y=10:x+y print sum2(1) #11 print sum2(1,100) #101 ```
参考资料:
http://www.cnblogs.com/BeginMan/p/3178103.html
这篇关于The Python Tutorial学习笔记(2)--map、reduce、filter介绍的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!