Welcome 微信登录

首页 / 操作系统 / Linux / Python 扯淡的Map-Reduce

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