教为学:Python学习之路(五):map reduce学习

教为学:Python学习之路(五):map reduce学习

前言

昨天的博客竟然被首页下架了,虽然水了点,总觉得可以查看帮助解决的内容,不值得花太多的功夫。

说到map reduce,第一反应是Hadoop的map reduce函数编程。

不过我们这里要讲的python,有时间可以写写Hadoop的map reduce。

Lamdba函数

要了解map reduce,首先得了解Lamdba函数,Lamdba函数顾名思义就是匿名函数。园子里很多时候关于c#和java之争的时候,匿名函数都会作为c#的一个优点陈列在前,某种意义上,这是对匿名函数能力的认可。Java在最新版本中也计划把匿名函数给加进来,同样也是对匿名函数的认可。

所谓匿名函数就是没有名字的函数,没有名字的函数怎么调用。

正常的函数及其调用:

  1. def f(x):
  2.     return 2*x
  3. print f(3)
  4. #结果
  5. 6

F是函数名。

F(3)是调用函数。

不正常函数(匿名函数)及其调用:

  1. g = lambda x:x*2
  2. print g(3)
  3. #结果
  4. 6

G算什么?

好像还是函数名。

那我们来个更彻底的。

  1. print (lambda x:x*2)(3)
  2. #结果
  3. 6

连f和g都彻底没了。

这东西有什么用?

Map函数

所有的函数,我先上的是这么句话。

  1. help(map)
  2. #结果
  3. map(...)
  4.     map(function, sequence[, sequence, ...]) -> list
  5.  
  6.     Return a list of the results of applying the function to the items of
  7.     the argument sequence(s). If more than one sequence is given, the
  8.     function is called with an argument list consisting of the corresponding
  9.     item of each sequence, substituting None for missing values when not all
  10.     sequences have the same length. If the function is None, return a list of
  11.     the items of the sequence (or a list of tuples if more than one sequence).

看了这个帮助,大家就应该清楚,匿名函数这个东西用在哪里吧!

上个例子再解释这个函数:

  1. print map(lambda x:x*2,[1,2,3,4])
  2. #结果
  3. [2, 4, 6, 8]

函数参数是一个函数,然后把后面的序列里面的值一个个传入这个函数,最后返回一个列表。

Reduce函数

国际惯例:

  1. help(reduce)
  2. #结果
  3. reduce(...)
  4.     reduce(function, sequence[, initial]) -> value
  5.  
  6.     Apply a function of two arguments cumulatively to the items of a sequence,
  7.     from left to right, so as to reduce the sequence to a single value.
  8.     For example, reduce(lambda x, y: x+y, [1, 2, 3, 4, 5]) calculates
  9.     ((((1+2)+3)+4)+5). If initial is present, it is placed before the items
  10.     of the sequence in the calculation, and serves as a default when the
  11.     sequence is empty.

这次的帮助还有个小例子,那么,我们就运行一下这个小例子吧。

  1. print reduce(lambda x,y:x+y,[1,2,3,4,5])
  2. #结果
  3. 15

第一个参数函数必须有两个参数,不然,这东西玩不下去了。

把序列中的第一个和第二个元素作为参数传递给函数,然后把返回值和第三个元素传递给函数,然后把返回值和第四个元素传递给参数,以此类推,其实上面的结果是((((1+2)+3)+4)+5)

Filter函数

继续国际惯例:

  1. help(filter)
  2. #结果
  3. filter(...)
  4.     filter(function or None, sequence) -> list, tuple, or string
  5.  
  6.     Return those items of sequence for which function(item) is true. If
  7.     function is None, return the items that are true. If sequence is a tuple
  8.     or string, return the same type, else return a list.

再上例子:

  1. print filter(lambda x:x%2==1,[1,2,3,4])
  2. 结果
  3. [1, 3]

人如其名,过滤器,把满足要求的序列过滤出来。

第一个参数还是个函数,不过相比其他几个,这次可以为none。

函数只能返回布尔值,作为判断条件。

也就是说,序列里面满足函数判断条件的值全部返回出来。

posted @ 2013-06-06 22:38  教为学  阅读(1158)  评论(0编辑  收藏  举报