博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
python 中的map(), reduce(), filter
阅读量:7173 次
发布时间:2019-06-29

本文共 1791 字,大约阅读时间需要 5 分钟。

据说是函数式编程的一个函数(然后也有人tucao py不太适合干这个),在我看来算是pythonic的一种写法。

简化了我们的操作,比方我们想将list中的数字都加1,最基本的可能是编写一个函数:

In [40]: def add_one(i):   ....:     return i+1   ....: In [41]: for i in range(1, 3):   ....:     print add_one(i)   ....:     23

如果使用map就简单一些了:

In [42]: map(add_one, range(1, 3))Out[42]: [2, 3]

 

其实这里还不够pythonic, 毕竟我们忘记了还有lambda这个匿名函数

 

In [44]: map(lambda x: x+1, range(1, 3))Out[44]: [2, 3]

 

 reduce的作用是对可迭代对象依次做某种操作,比方说依次相加或者乘之类的

内置的说明如下:

Help on built-in function reduce in module __builtin__:reduce(...)    reduce(function, sequence[, initial]) -> value        Apply a function of two arguments cumulatively to the items of a sequence,    from left to right, so as to reduce the sequence to a single value.    For example, reduce(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.(END)

 使用方法如下:

In [18]: reduce(lambda x, y: x*y, [1, 2, 3])Out[18]: 6
In [19]: reduce(lambda x, y: x*y, [1])Out[19]: 1In [20]: reduce(lambda x, y: x*y, [], 0)  # 最后一个为初始值Out[20]: 0

  

 

filter是对可迭代对象做某种过滤,使用方法和上面两个相似:

Help on built-in function filter in module __builtin__: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.
In [22]: filter(lambda x: x > 5, range(10))Out[22]: [6, 7, 8, 9]

 

 

基本使用方法大致如上,可能觉得刚开始觉得用处不大,实际上用习惯了就会觉得十分顺手

比方说让大家求1到100的和,可能函数写出来也只有几行代码,但是你用reduce呢,就只有一行。

大家可以试着用这种方法算一下 1!+2!+...+100!

 

 (发现内置的文档已经很赞了~

 

参考见:

 

https://eastlakeside.gitbooks.io/interpy-zh/content/Map%20&%20Filter/index.html

转载地址:http://hmbzm.baihongyu.com/

你可能感兴趣的文章
Security Software Engineer
查看>>
UVa294 Divisors
查看>>
洛谷P3406 海底高铁
查看>>
HTML学习
查看>>
Warriors of the Visual Studio, Assemble! (Visual Studio的勇士们,汇编吧!)
查看>>
使用Aouth2进行身份验证
查看>>
我们有助教啦
查看>>
一个有关原型的问题牵扯出的问题
查看>>
P53 T3
查看>>
关于 tensorflow-gpu 中 CUDA 和 CuDNN 版本适配问题
查看>>
1、JUC--volatile 关键字-内存可见性
查看>>
LeetCode: Minimum Depth of Binary Tree
查看>>
可运行的代码
查看>>
Oracle数据库添加新字段后加载页面报错 java.lang.IllegalArgumentException
查看>>
CSU 1505: 酷酷的单词【字符串】
查看>>
198. 打家劫舍
查看>>
错误之处(二)
查看>>
解决insert语句插入时,需要写列值的问题
查看>>
CSS选择器 < ~ +
查看>>
Opengl_es模型矩阵位置:glFrustumx与glTranslatef参数的相互影响--立方体旋转特效
查看>>