Python 扯淡的Map-Reduce
发现python具有类似Hadoop中的Map-reduce概念的标准函数,于是变搞来玩玩,发现还是蛮好玩的,虽然功能简陋了点,不过该做的都做了。map(func, *iterables) --> map objectMake an iterator that computes the function using arguments fromeach of the iterables.Stops when the shortest iterable is exhausted.func是一个函数,该函数具有的参数个数根据后面iterables个数来确定,对iterables中的每个元素都作为参数调用一次func函数,并且将结果返回。也就是说调用了多少次func,就会返回多少次结果。
该map的实现是一个采用的是生成器,也就是说调用一次__next__(),才会调用一次函数返回结果。
def func(x,y):return x*y*2list=result=map(func,list,list)print(result.__next__())for r in result:print(r)结果:2 8 18 32 50
其实map函数我们自己也可以实现一个版本:
def map(func,*iters):for it in zip(*iters):yield func(*it)#一定要星号*,表示需要将it元组各个元素作为多个参数,而不是将整个列表作为一个参数
注:以上记过python 3.2测试通过,python 3以上版本apply(),callable(),exefile(),file(),reduce(),reload()等方法都被移除了。
页:
[1]