首页 > 代码库 > 【python】filter,map和reduce函数介绍

【python】filter,map和reduce函数介绍

filter(function, iterable)
map(function, iterable)
reduce(function, sequence)

filter将 function依次作用于iterable的每个元素,如果返回值为true, 保留元素,否则从iterable里面删除。function必须返回是一个bool类型的函数。
例如:
def test(x):    return (x > 3)filter(test, [1, 2, 3, 4, 5]) =====> [4, 5]

map将function作用于iterable每个元素,将对应输出结果保存为一个list。function具有返回值。

例如
def add(x):    return (1 + x)map(test, [1, 2, 3, 4, 5]) =====> [2, 3, 4, 5, 6]

reduce先把iterable的前两个元素调用函数 function,再以返回值和第三个参数调用,依次执行下去

def add(x,y): return x+yreduce(add, range(1, 11))55