map()函数
Python中的map()函数接收两个参数,一个是调用函数对象(python中处处皆对象,函数未实例前也可以当对象一样调用),另一个是调用函数所需要的参数,返回值是迭代计算出的结果所组成的列表。
def func(x): return x*x r=map(func,[1,2,3,4,5,6,7,8,9]) l=list(r) print(l)
显示结果:
[1, 4, 9, 16, 25, 36, 49, 64, 81]
reduce() 函数
reduce函数同样需要两个参数,一个是调用函数对象,另一个数调用函数所需要的参数,其返回值是将计算结果继续和下一个元素做累积。
from functools import reduce def add(x,y): print('x is:',x,'y is:',y) return x+y ret=reduce(add,[1,3,5,7,9]) print(ret)
显示结果:
x is: 1 y is: 3 x is: 4 y is: 5 x is: 9 y is: 7 x is: 16 y is: 9 25
from functools import reduce def add(x,y): print('x is:',x,'y is:',y) return x*10+y ret=reduce(add,[1,3,5,7,9]) print(ret)
显示结果:
x is: 1 y is: 3 x is: 13 y is: 5 x is: 135 y is: 7 x is: 1357 y is: 9 13579
以上就是python中map函数和reduce函数的使用方法介绍(附代码)的详细内容,更多请关注Gxl网其它相关文章!
查看更多关于python中map函数和reduce函数的使用方法介绍(附代码)的详细内容...
声明:本文来自网络,不代表【好得很程序员自学网】立场,转载请注明出处:http://haodehen.cn/did83609