Python内置函数
Python内建了map()和reduce()函数
1、map函数有2个入参,函数和Iterable,当希望将一个函数作用在 一系列数据上时,可以调用map函数,返回值是一个Iterator,例如:
def f(x):
return x*x
list = [1,2,3,4]
s = map(f,list)
print(s)
print(next(s))
输出结果为:
<map object at 0x0000000003474E10>
1
上述代码如果直接输出:
print(list(s))
系统会报如下错误:
Traceback (most recent call last):
File "D:\work\python\study.py", line 8, in <module>
print(list(s))
TypeError: 'list' object is not callable
原因是list()是系统自带的,你不能在用它的时候自己同时定义一个别的叫做list的变量,这样会冲突,将上述变量list改成list1就好了
def f(x):
return x*x
list1 = [1,2,3,4]
s = map(f,list1)
print(list(s))
输出结果为:[1, 4, 9, 16]
由于结果s是一个Iterator,Iterator是惰性序列,因此通过list()函数让它把整个序列都计算出来并返回一个list。
2、reduce()函数
reduce把一个函数作用在一个序列[x1, x2, x3, …]上,这个函数必须接收两个参数,reduce把结果继续和序列的下一个元素做累积计算,其效果就是:
reduce(f, [x1, x2, x3, x4]) = f(f(f(x1, x2), x3), x4)
例如:
from functools import reduce
def f(x,y):
return x+y
re = [1,2,3,4]
s = reduce(f,re)
print(s)
要调用reduce函数,必须有from functools import reduce