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)

三、 map、reduce的一个应用场景

from collections import reduce


# str 转换成 float
def str2float(s):
    n = s.index('.')
    return reduce(lambda x, y: x*10 + y, map(int, [x for x in s if x != '.']))/10**(len(s)-n-1)



if __name__ == "__main__":
    str2float('123.456')

四、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)

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值