The Python Tutorial学习笔记(2)--map、reduce、filter介绍

来源:互联网 发布:tcp协议端口号 编辑:程序博客网 时间:2024/05/16 18:17

The Python Tutorial学习笔记(2)–map、reduce、filter介绍


  1. 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]

“`

  1. map

    ==map(function, iterable, …)==

    function 可以处理一个或者多个序列里边的位置相互对应的函数,
    function 可以为空,具体体现在一下代码测试中:

    1. 当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 序列不发生变化#当函数只有一个参数时处理多个序列是则发生异常
    2. 当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]#按照匿名函数对两个序列位置对应的元素进行计算最后返回结果序列
    3. 当function的参数为两个以上是,依次类推。

  2. 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 reduce    TypeError: '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 = initializer    for x in it:        accum_value = function(accum_value, x)    return accum_value```
  3. lambda

    lambda函数为匿名函数,python lambda它只是一个表达式,而def则是一个语句。lambda表达式运行起来像一个函数,当被调用时创建一个框架对象。具体详见:http://www.cnblogs.com/BeginMan/p/3178103.html

    ```def add(x,y):return x+yadd2 = lambda x,y:x+yprint add2(1,2)     #3def sum(x,y=10):return x+ysum2 = lambda x,y=10:x+yprint sum2(1)       #11print sum2(1,100)   #101```
参考资料:
http://www.cnblogs.com/BeginMan/p/3178103.html
1 0
原创粉丝点击