zoukankan      html  css  js  c++  java
  • Python的map、filter、reduce函数

    map函数,对seq列表的每一个元素调用func函数,形成一个新的列表,map函数返回此新的列表。
    map函数python实现代码:

    1 def map(func,seq):
    2 mapped_seq = []
    3 for eachItem in seq:
    4 mapped_seq.append(func(eachItem))
    5 return mapped_seq

    filter函数的功能相当于过滤器。调用一个返回值为bool型的函数bool_func,来遍历每个seq中的元素,返回seq中由所有符合要求元素生成的新列表。
    filter函数python代码实现:

    1 def filter(bool_func,seq):
    2 filtered_seq = []
    3 for eachItem in seq:
    4 if bool_func(eachItem):
    5 filtered_seq.append(eachItem)
    6 return filtered_seq

    reduce函数,从seq列表中去两个元素传给bin_func作为参数, 计算结果作为bin_func的第一个参数,再从seq列表中取一个元素,作为bin_func的第二个参数,依次类推,直到遍历完所有seq中的元素,返回计算结果res。

    --bin_func必须为二元函数。

    --python3.x中已移除此函数。
    reduct函数python代码实现:

    1 def reduce(bin_func,seq,initial=None):
    2 lseq = list(seq)
    3 if initial is None:
    4 res = lseq.pop(0)
    5 else:
    6 res = initial
    7 for eachItem in lseq:
    8 res = bin_func(res,eachItem)
    9 return res

     举例说明: 

    1 def add(x, y):
    2 return x + y
    3 print reduce(add,[1,2,3,4])
    4 >>>10

    计算过程演示如下:

    1 reduce(add,[1,2,3,4])
    2 res = add(1,2)
    3 res = add(res,3)
    4 res = add (res,4)
    5 return res

    亲,明白了么,好像明白了。





  • 相关阅读:
    总结ORACLE学习8023
    set @CurrentID=@@IDENTITY
    一个IT人:跳槽一定要谨慎
    SQL Server数据库开发(转自CSDN)
    46个不得不知的生活小常识
    CodeProjectSome Cool Tips For .Net 之一
    数据库原理综合习题答案
    EDM
    CodeProject Some Cool Tips for .NET之二
    The operation is not valid for the state of the transaction.
  • 原文地址:https://www.cnblogs.com/evening/p/2428413.html
Copyright © 2011-2022 走看看