问题导读
1.Map函数怎样输出执行结果? 2.Reduce函数的调用有什么特点?
一 概念介绍 本文从求质数,求阶乘两个示例, 提示Python的内置函数【map、reduce、filter】的使用方式
Map函数: 对iterable中的item依次执行function(item),执行结果输出为list
- map(function, iterable[, iterable, ...]) -> list
复制代码
Filter函数:对iterable中的item依次执行function(item),将执行结果为True(!=0)的item组成一个List/String/Tuple(取决于iterable的类型)返回,False则退出(0),进行过滤。
- filter(function or None, iterable) -> list, tuple, or string
复制代码
Reduce函数: iterable中的item顺序迭代调用function,函数必须要有2个参数。要是有第3个参数,则表示初始值,可以继续调用初始值,返回一个值 定义大致如下:
- def reduce(function, iterable, initializer=None):
- it = iter(iterable)
- if initializer is None:
- try:
- initializer = next(it)
- except StopIteration:
- raise TypeError('reduce() of empty sequence with no initial value')
- accum_value = initializer
- for x in it:
- accum_value = function(accum_value, x)
- return accum_value
复制代码
二 示例代码
- #!/usr/bin/python
- # encoding=utf-8
- # Filename: lambda.py
- # 测试程序
-
- # 质数的定义 只有1和它本身两个因数
- def isPrime(start, stop):
- # 取出质数,x从range(start,stop+1) 取的数
- return filter(lambda x : not [x % i for i in range(2, x) if x % i == 0], range(start, stop + 1))
-
- # 实现5!+4!+3!+2!+1!
- def addFactorial(n):
- result = []
- for i in map(lambda x:x + 1, range(n)):
- a = reduce(lambda x, y:x * y, map(lambda x:x + 1, range(i)))
- result.append(a)
- return reduce(lambda x, y:x + y, result)
-
-
- def main():
- # 设置默认值
- start = 2
- stop = 0
- n=1
- try :
- start = input("Enter a start Number :")
- stop = input("Enter a stop Number :")
- n = input("Enter a Number(int) : ")
- except :
- pass
- result = isPrime(start, stop)
- print(result)
- print addFactorial(n)
-
- if __name__ == '__main__':
- main()
复制代码
|