python map、reduce、filter详解

一、 map详解

>>> help(map)
Help on class map in module builtins:


class map(object)
 |  map(func, *iterables) --> map object
 |
 |  Make an iterator that computes the function using arguments from
 |  each of the iterables.  Stops when the shortest iterable is exhausted.
 |
 |  Methods defined here:
 |
 |  __getattribute__(self, name, /)
 |      Return getattr(self, name).
 |
 |  __iter__(self, /)
 |      Implement iter(self).
 |
 |  __new__(*args, **kwargs) from builtins.type
 |      Create and return a new object.  See help(type) for accurate signature.
 |
 |  __next__(self, /)
 |      Implement next(self).
 |
 |  __reduce__(...)

 |      Return state information for pickling.

map接受两个参数,func处理可迭代对象元素的函数,iterables可迭代对象,map会将iterables每个元素传给func做参数,返回func处理后的一个可迭代对象,如果func为None,则map等同于zip函数。

示例如下:

# coding = utf-8
from collections import Iterable


def get_right_name(my_list):
    """
    把不规范的英文名字,变为首字母大写,其他小写的规范名字。
    """
    if not isinstance(my_list, Iterable):
        raise ValueError("my_list must be a Iterator")

    def handel_str(name):
        return name.title()
    return map(handel_str, my_list)


if __name__ == "__main__":
    name_list = ['green', 'MICHEAL', 'jOHn']
    for a in get_right_name(name_list):
        print(a)

二、reduce详解

>>> from functools import reduce
>>> help(reduce)
Help on built-in function reduce in module _functools:


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.

参数:

function: 处理的函数;

sequence:可迭代对象;

initial :若果提供该参数,已该参数和可迭代对象第一个元素作为参数传给function,否则传可迭代对象的前两个参数。

如文档:reduce(lambda x, y: x+y, [1, 2, 3, 4, 5])返回((((1+2)+3)+4)+5)

示例求积:

from functools import reduce


def prod(iter_list):
    """
    对list中的元素求积
    :param iter_list:
    :return:
    """
    if not isinstance(iter_list, Iterable):
        raise ValueError("iter_list must be a Iterator")
    return reduce(lambda x, y: x*y, iter_list)

三、filter详解

class filter(object)
 |  filter(function or None, iterable) --> filter object
 |
 |  Return an iterator yielding those items of iterable for which function(item)

 |  is true. If function is None, return the items that are true.

参数:

function:传入的函数,可以为None

iterable:可迭代对象

return:返回一个filter可迭代对象,返回function(item)为True的元素,如果function为None返回item为true的元素。

示例:

def filter_demo(iter_list):
    if not isinstance(iter_list, Iterable):
        raise ValueError("iter_list must be iterable")
    return filter(lambda x: x % 2 == 0, iter_list)

猜你喜欢

转载自blog.csdn.net/qq_36255988/article/details/80300894