Map,Filter和Reduce

    • 转自:https://www.aliyun.com/jiaocheng/444967.html?spm=5176.100033.1.13.xms8KG
    • 摘要:Map,Filter和Reduce三个函数能为函数式编程提供便利。通过实例一个一个讨论并理解他们。Mapmap会将一个函数映射到一个输入列表的所有元素上。这是它的规范:规范:map(function_to_apply,list_of_inputs)大多数时候,我们要把列表中的所有元素一个个的传递给一个函数,并收集输出。比方说:items=[1,2,3,4,5]squared=[]foriinitems:squared.append(i**2)Map可以让我们用一种简单而漂亮的
    • Map,Filter和Reduce三个函数能为函数式编程提供便利。通过实例一个一个讨论并理解他们。
      Mapmap会将一个函数映射到一个输入列表的所有元素上。这是它的规范:规范:map(function_to_apply, list_of_inputs)大多数时候,我们要把列表中的所有元素一个个的传递给一个函数,并收集输出。比方说:items = [1, 2, 3, 4, 5]squared = [ ]for i in items: squared.append(i**2)Map可以让我们用一种简单而漂亮的多的方式来实现。items = [1, 2, 3, 4, 5]squared = list(map(lambda x : x**2, items))大多数时候,我们使用匿名函数(lambdas)来配合map。 map不仅可以用于一列表的输入,我们甚至可以用于一列表的函数def multiply(x): return (x*x)def add(x): return (x+x)funcs = [multiply, add]for i in range(5): value = map(lambda x: x(i), funcs) print(list(value))# Output:# [0, 0]# [1, 2]# [4, 4]# [9, 6]# [16, 8]
      Filter顾名思义,filter过滤列表中的元素,并且返回一个由所有符合要求的元素所构成的列表。符合要求即函数映射到该元素时返回值为Truenumber_list = range(-5, 5)less_than_zero = filter(lambda x : x<0, number_list)print list(less_than_zero)#output: [-5, -4, -3, -2, -1]这个filter类似一个for循环,但是它是一个内置函数,并且更快。
      Reduce当需要对一个列表进行一些计算并返回结果时,reduce是一个很有用的函数。举个例子,当你需要计算一个整数列表的乘积时。通常在python中,你可能会使用基本的for循环来完成这个任务。product = reduce((lambda x, y: x * y), [1, 2, 3, 4])# output: 24
      这里你能体会到了reduce与map的区别了吗,如果不能我们来个leetcode小算法题来体会一下题目:Given an array of integers, every element appears twice except for one. Find that single one.题目的大意应该好懂,就是有个数组,里面的数都出现了两次除了有一个只出现了一次,找出那个只出现了一次的数。拿到这个题目啊,我就想到了用python的内置collections,有一个Counter()函数,代码如下:def singleNumber1(nums): a = Counter(nums) for i in set(nums): if a[i] == 1: return i上面的几行代码确实可以完成题目,但是如果说你没有想到counter()函数呢?还有一个办法就是异或!异或这个性质真的超好用啊!一行解决问题:import operatordef singleNumber2(nums): return reduce(operator.xor, nums)这里用到了reduce,一行搞定,不得不感慨python的牛逼啊~

posted on 2018-05-29 16:46  枫飞飞  阅读(177)  评论(0编辑  收藏  举报