kingbosster 发表于 2015-4-25 11:41:16

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

教为学:Python学习之路(五):map reduce学习
前言
  昨天的博客竟然被首页下架了,虽然水了点,总觉得可以查看帮助解决的内容,不值得花太多的功夫。
  说到map reduce,第一反应是Hadoop的map reduce函数编程。
  不过我们这里要讲的python,有时间可以写写Hadoop的map reduce。
Lamdba函数
  要了解map reduce,首先得了解Lamdba函数,Lamdba函数顾名思义就是匿名函数。园子里很多时候关于c#和java之争的时候,匿名函数都会作为c#的一个优点陈列在前,某种意义上,这是对匿名函数能力的认可。Java在最新版本中也计划把匿名函数给加进来,同样也是对匿名函数的认可。
  所谓匿名函数就是没有名字的函数,没有名字的函数怎么调用。
  正常的函数及其调用:

[*]
def f(x):
[*]
    return 2*x
[*]
print f(3)
[*]
#结果
[*]
6
  F是函数名。
  F(3)是调用函数。
  不正常函数(匿名函数)及其调用:

[*]
g = lambda x:x*2
[*]
print g(3)
[*]
#结果
[*]
6
  G算什么?
  好像还是函数名。
  那我们来个更彻底的。

[*]
print (lambda x:x*2)(3)
[*]
#结果
[*]
6
  连f和g都彻底没了。
  这东西有什么用?
Map函数
  所有的函数,我先上的是这么句话。

[*]
help(map)
[*]
#结果
[*]
map(...)
[*]
    map(function, sequence[, sequence, ...]) -> list
[*]
[*]
    Return a list of the results of applying the function to the items of
[*]
    the argument sequence(s). If more than one sequence is given, the
[*]
    function is called with an argument list consisting of the corresponding
[*]
    item of each sequence, substituting None for missing values when not all
[*]
    sequences have the same length. If the function is None, return a list of
[*]
    the items of the sequence (or a list of tuples if more than one sequence).
  看了这个帮助,大家就应该清楚,匿名函数这个东西用在哪里吧!
  上个例子再解释这个函数:

[*]
print map(lambda x:x*2,)
[*]
#结果
[*]

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

[*]
help(reduce)
[*]
#结果
[*]
reduce(...)
[*]
    reduce(function, sequence[, initial]) -> value
[*]
[*]
    Apply a function of two arguments cumulatively to the items of a sequence,
[*]
    from left to right, so as to reduce the sequence to a single value.
[*]
    For example, reduce(lambda x, y: x+y, ) calculates
[*]
    ((((1+2)+3)+4)+5). If initial is present, it is placed before the items
[*]
    of the sequence in the calculation, and serves as a default when the
[*]
    sequence is empty.
  这次的帮助还有个小例子,那么,我们就运行一下这个小例子吧。

[*]
print reduce(lambda x,y:x+y,)
[*]
#结果
[*]
15
  第一个参数函数必须有两个参数,不然,这东西玩不下去了。
  把序列中的第一个和第二个元素作为参数传递给函数,然后把返回值和第三个元素传递给函数,然后把返回值和第四个元素传递给参数,以此类推,其实上面的结果是((((1+2)+3)+4)+5)
Filter函数
  继续国际惯例:

[*]
help(filter)
[*]
#结果
[*]
filter(...)
[*]
    filter(function or None, sequence) -> list, tuple, or string
[*]
[*]
    Return those items of sequence for which function(item) is true. If
[*]
    function is None, return the items that are true. If sequence is a tuple
[*]
    or string, return the same type, else return a list.
  再上例子:

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

  人如其名,过滤器,把满足要求的序列过滤出来。
  第一个参数还是个函数,不过相比其他几个,这次可以为none。
  函数只能返回布尔值,作为判断条件。
  也就是说,序列里面满足函数判断条件的值全部返回出来。
页: [1]
查看完整版本: 教为学:Python学习之路(五):map reduce学习