首页 行业资讯 宠物日常 宠物养护 宠物健康 宠物故事

怎么用Python写mapreduce,请举例说明,初学者,请赐教,不胜感激

发布网友

我来回答

1个回答

热心网友

1.lambda

# 匿名函数
# 基本用法 lambda x: x**2
    # 第一个参数,然后是表达式
# 也可以使用如下
(lambda x: x**2)(5)

2. map()

def map(function, sequence, *sequence_1): # real signature unknown; restored from __doc__
    """
    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).
    """
    return []
 
# 两个参数,一个处理函数,一个可迭代的序列
# 返回一个列表
 
# 例如 计算1到10的平方,并以列表的形式返回
map(lambda x: x**2, range(1, 11))
# 结果如下
[1, 4, 9, 16, 25, 36, 49, , 81, 100]
 
# 当然 也可以如下这样使用
def square(x):
    return x**2
 
map(square, range(1, 11))

3.rece()

def rece(function, sequence, initial=None): # real signature unknown; restored from __doc__
    """
    rece(function, sequence[, initial]) -> value
     
    Apply a function of two arguments cumulatively to the items of a sequence,
    from left to right, so as to rece the sequence to a single value.
    For example, rece(lambda x, y: x+y, [1, 2, 3, 4, 5]) 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.
    """
    pass
 
# 两个参数,一个接受两个参数的函数,一个序列参数
# 例如 计算 1到10 的和
rece(lambda x, y: x+y, range(1, 11))
 
# 当然,不适用lambda匿名函数也可以
def add(x, y):
    return x+y
rece(add, range(1, 11))
 
# 结果如下
45

4.filter()

def filter(function_or_none, sequence): # known special case of 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.
    """
    pass
 
# 接受两个参数,一个过滤函数,返回True 或者 False, 以及一个序列
# 例如, 计算100以内的偶数
filter(lambda x: x % 2 == 0, range(100))
 
# 如上
def div2(x):
    if x % 2 == 0:
        return True
    else:
        return False
filter(div2, range(100))
 
# 结果如下 
[0, 2, 4, 6, 8, 10, 12, 14, 16, ... ]

声明声明:本网页内容为用户发布,旨在传播知识,不代表本网认同其观点,若有侵权等问题请及时与本网联系,我们将在第一时间删除处理。E-MAIL:11247931@qq.com