0%

python map and reduce

map 与 reduce函数

  1. map()函数接收两个参数, 第一个是函数, 第二个是Iterable, map将传入的函数依次作用到序列的每个元素, 并将结果作为新的Iterator返回

    1
    2
    3
    4
    5
    6
    7
    8
    def square(x):
    return x ** 2
    r = map(square, [1,2,3,4,5])
    squareed_list = list(r)
    print(squreed_list) # [1,4,9,16,25]
    #使用lambda匿名函数简化为一行代码
    list(map(lambda x: x*x, [1,2,3,4,5]))
    list(map(str, [1,2,3])) # ['1', '2', '3']

    注意map函数返回的是一个Iterator(惰性序列), 要通过list函数转化为常用列表结构。

  2. reduce()函数接收两个参数, 一个是函数(两个参数), 一个是序列, 与map不同的是,reduce把结果和序列的下一个元素做累积计算。

    1
    reduce(f, [x1, x2, x3, x4]) = f(f(f(x1, x2), x3), x4)
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    from functools import reduce
    CHAR_TO_INT = {
    '0': 0,
    '1': 1,
    '2': 2,
    '3': 3,
    '4': 4,
    '5': 5,
    '6': 6,
    '7': 7,
    '8': 8,
    '9': 9
    }
    def str2int(str):
    ints = map(lambda x: CHAR_TO_INT[x], str)
    return reduce(lambda x,y: 10*x + y, ints)
    print(str2int('0012345')) # 0012345