python专题python干货

python | map,reduce详解

2020-04-17  本文已影响0人  yuanCruise

map()方法的调用方法为:map(function_to_apply, list_of_inputs)

如下代码所示,展示了map的使用方式,比如对输入的三个序列中的值进行减均值,除方差的操作。

def map_f(x,y,z):
    mean = 128
    std = 1
    x = (x-mean)/std
    y = (y-mean)/std
    z = (z-mean)/std
    return x,y,z

if __name__ == "__main__":
    input_map_list_r = [126, 127, 128, 129, 130]
    input_map_list_g = [126, 127, 128, 129, 130]
    input_map_list_b = [126, 127, 128, 129, 130]
    output_map_list = map(map_f,input_map_list_r,input_map_list_g,input_map_list_b)
    output_map_list_2 = map(lambda x,y,z:((x -128)/1,(y -128)/1,(z -128)/1), input_map_list_x,input_map_list_y,input_map_list_z )

    for i in output_map_list:
        print(i)

output:
(-2.0, -2.0, -2.0)
(-1.0, -1.0, -1.0)
(0.0, 0.0, 0.0)
(1.0, 1.0, 1.0)
(2.0, 2.0, 2.0)

该函数中还顺便介绍了一下匿名函数的使用方式。如下代码所示,匿名函数lambda的作用就相当于上述代码中的def map_f(x,y,z),其作用就是把函数平铺到了代码中。

map(lambda x,y,z:((x -128)/1,(y -128)/1,(z -128)/1),\
 input_map_list_x,input_map_list_y,input_map_list_z )

reduce()方法的调用方法为:reduce(function_to_apply, list_of_inputs)

如下代码所示,利用reduce函数就可以实现1-100的自然数求和操作。


from functools import reduce

def add_f(x,y):
    return x+y

if __name__ == "__main__":
    items = range(1,101)
    result = reduce(add_f,items)
    print(result)
上一篇 下一篇

猜你喜欢

热点阅读