Python中filter、map、reduce函数
来源:互联网 发布:粉红女郎 知乎 编辑:程序博客网 时间:2024/05/22 13:53
概述
map filter
- python 3 中,map和filter返回生成器,因此他们的直接替代品是生成器表达式;
- Python 2中,这两个函数返回的是列表,直接替代品是列表推导式;
- filter是用于过滤的生成器函数,map是用于映射的生成器函数;即:
filter中的函数返回的是原可迭代对象进行筛选后的结果,map函数返回的是重新创建的新的可迭代对象。
reduce
- Python 2 中,reduce是内置函数;
- Python 3中,reduce放到了functools模块中了;
- 该函数最常用于求和,但Python2.3以后,求和来说,内置函数sum在可读性和性能方面更优。
filter(function, iterable)
function 函数名
iterable 可迭代对象
filter中的函数返回布尔值,可迭代对象通过迭代,将元素传入函数,通过函数返回的布尔值来判断该元素是保留还是丢弃。
In [178]: def a(item): ...: return item - 2In [179]: list(filter(a,range(5)))Out[179]: [0, 1, 3, 4]
map(function,it1, ,[it2,…,itN])
function 函数名
it 可迭代对象
- 通过迭代,将元素传入函数,经过函数处理后,将函数的返回值放入到新的可迭代对象中;
- 调用map函数的结果是是重新创建并返回了新的可迭代对象;
- map可以接收多个可迭代对象,如果传入n个,那么func必须可以接受n个参数,而且要并行处理各个可迭代对象。
python 2 中使用map函数效率低些,因为map函数要使用结果构建一个列表;
在Python 3 中,map函数是惰性的,它会创建一个生成器,按需产出结果,因此能节省内存。
In [172]: list(map(lambda x:x+5,range(5)))Out[172]: [5, 6, 7, 8, 9]
In [171]: list(map(lambda x,y:x+y,range(5),range(5)))Out[171]: [0, 2, 4, 6, 8]
reduce(function, iterable, [initial])
function 函数名
iterable 可迭代对象
initial 如果提供了initial,把它当做第一个元素传入
与map不同的是,reduce里的函数必须传入两个形参,并且会把上一个元素在函数执行的结果累积到下一个元素。
In [174]: from functools import reduceIn [176]: ret = reduce(lambda x,y:x+y,range(5))In [177]: print(ret)10In [199]: ret2 = reduce(lambda x,y:x+y,range(5),10)In [200]: print(ret2)20
阅读全文
0 0
- python中map、filter、reduce 函数使用方法
- Python中filter、map、reduce函数
- python map函数,filter,reduce
- python map, reduce, filter 函数
- python-map()函数,reduce()函数,filter()函数
- python map函数,Filter函数,Reduce函数
- Python中reduce、map、filter、apply、tuple函数
- 关于python中,map,reduce,filter,sort函数的用法:
- 关于python中,map,reduce,filter,sorted函数的用法
- python中map,filter和reduce函数区别
- python中函数式编程map、reduce、filter的用法
- Python 中 map,reduce,和filter 内置函数的方法
- Python学习笔记: Python3中map、filter、reduce函数
- Python的map、filter、reduce函数
- Python的map、filter、reduce函数
- [Python] 函数lambda(), filter(), map(), reduce()
- [Python] 函数lambda(), filter(), map(), reduce()
- python内置函数map/reduce/filter
- repo init报错Cannot get https://gerrit.googlesource.com/git-repo/clone.bundle
- hehheda
- 数据结构第二周项目2--程序的多文件组织
- C++下Socket编程
- 苹果2017秋季大会回顾
- Python中filter、map、reduce函数
- Linux网络编程多线程模型
- (CodeForces
- 在ubuntu上搭建caffe环境
- CGAL 4.10 官方文档 软件包概述 ——算术与代数类
- Pandas 使用教程 4
- 【oracle】使用sys进行的操作
- Gulp.js介绍
- BUG汇总 1