Python中的map、reduce和filter浅析

 更新时间:2014年04月26日 10:46:29   作者:  
这篇文章主要介绍了Python中的map、reduce和filter,用实例来理解这3个函数,需要的朋友可以参考下

1、先看看什么是 iterable 对象

以内置的max函数为例子,查看其doc:

复制代码 代码如下:

>>> print max.__doc__
max(iterable[, key=func]) -> value
max(a, b, c, ...[, key=func]) -> value

With a single iterable argument, return its largest item.
With two or more arguments, return the largest argument.


在max函数的第一种形式中,其第一个参数是一个 iterable 对象,既然这样,那么哪些是 iterable 对象呢?
复制代码 代码如下:

>>> max('abcx')
>>> 'x'
>>> max('1234')
>>> '4'
>>> max((1,2,3))
>>> 3
>>> max([1,2,4])
>>> 4

我们可以使用yield生成一个iterable 对象(也有其他的方式):
复制代码 代码如下:

def my_range(start,end):
    ''' '''
    while start <= end:
        yield start
        start += 1

执行下面的代码:
复制代码 代码如下:

for num in my_range(1, 4):
    print num
print max(my_range(1, 4))

将输出:
复制代码 代码如下:

1
2
3
4
4


2、map

在http://docs.python.org/2/library/functions.html#map中如此介绍map函数:

复制代码 代码如下:

map(function, iterable, ...)
Apply function to every item of iterable and return a list of the results. If additional iterable arguments are passed, function must take that many arguments and is applied to the items from all iterables in parallel. If one iterable is shorter than another it is assumed to be extended with None items. If function is None, the identity function is assumed; if there are multiple arguments, map() returns a list consisting of tuples containing the corresponding items from all iterables (a kind of transpose operation). The iterable arguments may be a sequence or any iterable object; the result is always a list.

map函数使用自定义的function处理iterable中的每一个元素,将所有的处理结果以list的形式返回。例如:
复制代码 代码如下:

def func(x):
    ''' '''
    return x*x

print map(func, [1,2,4,8])
print map(func, my_range(1, 4))


运行结果是:
复制代码 代码如下:

[1, 4, 16, 64]
[1, 4, 9, 16]

也可以通过列表推导来实现:
复制代码 代码如下:

print [x*x for x in [1,2,4,8]]

3、reduce

在http://docs.python.org/2/library/functions.html#reduce中如下介绍reduce函数:

复制代码 代码如下:

reduce(function, iterable[, initializer])
Apply function of two arguments cumulatively to the items of iterable, from left to right, so as to reduce the iterable to a single value. For example, reduce(lambda x, y: x+y, [1, 2, 3, 4, 5]) calculates ((((1+2)+3)+4)+5). The left argument, x, is the accumulated value and the right argument, y, is the update value from the iterable. If the optional initializer is present, it is placed before the items of the iterable in the calculation, and serves as a default when the iterable is empty. If initializer is not given and iterable contains only one item, the first item is returned.

这个已经介绍的很明了,
复制代码 代码如下:
reduce(lambda x, y: x+y, [1, 2, 3, 4, 5])

相当于计算
复制代码 代码如下:

((((1+2)+3)+4)+5)

而:
复制代码 代码如下:

reduce(lambda x, y: x+y, [1, 2, 3, 4, 5],6)

相当于计算
复制代码 代码如下:

(((((6+1)+2)+3)+4)+5)


4、filter

在http://docs.python.org/2/library/functions.html#filter中如下介绍filter函数:

复制代码 代码如下:

filter(function, iterable)
Construct a list from those elements of iterable for which function returns true. iterable may be either a sequence, a container which supports iteration, or an iterator. If iterable is a string or a tuple, the result also has that type; otherwise it is always a list. If function is None, the identity function is assumed, that is, all elements of iterable that are false are removed.

Note that filter(function, iterable) is equivalent to [item for item in iterable if function(item)] if function is not None and [item for item in iterable if item] if function is None.


参数function(是函数)用于处理iterable中的每个元素,如果function处理某元素时候返回true,那么该元素将作为list的成员而返回。比如,过滤掉字符串中的字符a:
复制代码 代码如下:

def func(x):
    ''' '''
    return x != 'a'

print filter(func, 'awake')


运行结果是:
复制代码 代码如下:

wke

这也可以通过列表推导来实现:
复制代码 代码如下:

print ''.join([x for x in 'awake' if x != 'a'])

相关文章

  • 在Django的上下文中设置变量的方法

    在Django的上下文中设置变量的方法

    这篇文章主要介绍了在Django的上下文中设置变量的方法,Django是重多Python高人气框架中最为著名的一个,需要的朋友可以参考下
    2015-07-07
  • 在Python中将元组转换为列表的方法详解

    在Python中将元组转换为列表的方法详解

    这两种Python 数据类型看起来很相似,但在上下文中却有不同的用法,元组和列表之间的主要区别在于它们的可变性,仅当您需要修改元素时才会将元组转换为列表,本文现在我们将深入研究将元组转换为列表的不同方法,需要的朋友可以参考下
    2023-09-09
  • Python3进制之间的转换代码实例

    Python3进制之间的转换代码实例

    这篇文章主要介绍了Python3进制之间的转换代码实例,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下
    2019-08-08
  • 通过numba模块给Python代码提速的方法详解

    通过numba模块给Python代码提速的方法详解

    numba是Anaconda公司开发的针对Python的开源JIT编译器,用于提供Python版CPU和GPU编程,速度比原生Python快数十倍。本文将详细介绍一下numba是如何实现代码提速的,需要的可以参考一下
    2022-01-01
  • python之class类和方法的用法详解

    python之class类和方法的用法详解

    这篇文章主要介绍了python中class类和方法的用法详解,如果有不太清楚面向对象的类和方法的编程思想的小伙伴可以借鉴参考本文
    2023-03-03
  • python 默认参数问题的陷阱

    python 默认参数问题的陷阱

    本文给大家讲述的是python 默认参数问题的陷阱,有需要的小伙伴可以参考下
    2016-02-02
  • python字符串替换第一个字符串的方法

    python字符串替换第一个字符串的方法

    这篇文章主要介绍了python字符串替换第一个字符串的方法,本文通过实例代码给大家介绍的非常详细,具有一定的参考借鉴价值,需要的朋友可以参考下
    2019-06-06
  • PyTorch模型容器与AlexNet构建示例详解

    PyTorch模型容器与AlexNet构建示例详解

    这篇文章主要为大家介绍了PyTorch模型容器与AlexNet构建示例详解,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪
    2023-07-07
  • openCV入门学习基础教程第二篇

    openCV入门学习基础教程第二篇

    人脸识别,物体检测,OpenCV是基石,下面这篇文章主要给大家介绍了关于openCV入门学习基础教程的相关资料,文中通过实例代码介绍的非常详细,需要的朋友可以参考下
    2022-11-11
  • pandas处理csv文件的方法步骤

    pandas处理csv文件的方法步骤

    这篇文章主要介绍了pandas处理csv文件的方法步骤,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2020-10-10

最新评论