分享

从两个例子看 Python【map、reduce、filter】内置函数的使用

坎蒂丝_Swan 发表于 2015-1-14 10:27:44 [显示全部楼层] 回帖奖励 阅读模式 关闭右栏 1 11241

问题导读

1.Map函数怎样输出执行结果?
2.Reduce函数的调用有什么特点?








一 概念介绍
        本文从求质数,求阶乘两个示例, 提示Python的内置函数【map、reduce、filter】的使用方式

Map函数: 对iterable中的item依次执行function(item),执行结果输出为list

  1. map(function, iterable[, iterable, ...]) -> list
复制代码
Filter函数:对iterable中的item依次执行function(item),将执行结果为True(!=0)的item组成一个List/String/Tuple(取决于iterable的类型)返回,False则退出(0),进行过滤。
  1. filter(function or None, iterable) -> list, tuple, or string  
复制代码


Reduce函数: iterable中的item顺序迭代调用function,函数必须要有2个参数。要是有第3个参数,则表示初始值,可以继续调用初始值,返回一个值
    定义大致如下:

  1. def reduce(function, iterable, initializer=None):
  2.     it = iter(iterable)
  3.     if initializer is None:
  4.         try:
  5.             initializer = next(it)
  6.         except StopIteration:
  7.             raise TypeError('reduce() of empty sequence with no initial value')
  8.     accum_value = initializer
  9.     for x in it:
  10.         accum_value = function(accum_value, x)
  11.     return accum_value
复制代码

二 示例代码
  1. #!/usr/bin/python
  2. # encoding=utf-8
  3. # Filename: lambda.py
  4. # 测试程序
  5. # 质数的定义 只有1和它本身两个因数
  6. def isPrime(start, stop):
  7.     # 取出质数,x从range(start,stop+1) 取的数
  8.     return filter(lambda x : not [x % i for i in range(2, x) if x % i == 0], range(start, stop + 1))
  9. # 实现5!+4!+3!+2!+1!
  10. def addFactorial(n):
  11.     result = []  
  12.     for i in map(lambda x:x + 1, range(n)):
  13.         a = reduce(lambda x, y:x * y, map(lambda x:x + 1, range(i)))  
  14.         result.append(a)  
  15.     return reduce(lambda x, y:x + y, result)
  16. def main():
  17.     # 设置默认值
  18.     start = 2
  19.     stop = 0
  20.     n=1
  21.     try :
  22.         start = input("Enter a start Number :")
  23.         stop = input("Enter a stop  Number :")
  24.         n = input("Enter a Number(int) : ")
  25.     except :
  26.         pass
  27.     result = isPrime(start, stop)
  28.     print(result)
  29.     print addFactorial(n)
  30.      
  31. if __name__ == '__main__':
  32.     main()
复制代码






欢迎加入about云群90371779322273151432264021 ,云计算爱好者群,亦可关注about云腾讯认证空间||关注本站微信

已有(1)人评论

跳转到指定楼层
落魂草 发表于 2015-1-14 20:21:01
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

关闭

推荐上一条 /2 下一条