python2.7 与 python3.4 中的filter
来源:互联网 发布:哈尔滨网络电视台 编辑:程序博客网 时间:2024/06/05 09:05
- ## python2.7 filter使用
Python内建的filter()
函数用于过滤序列。
和map()
类似,filter()
也接收一个函数和一个序列。和map()
不同的时,filter()
把传入的函数依次作用于每个元素,然后根据返回值是True
还是False
决定保留还是丢弃该元素。
例如,在一个list中,删掉偶数,只保留奇数,可以这么写:
def is_odd(n):
return n % 2 == 1
filter(is_odd, [1, 2, 4, 5, 6, 9, 10, 15]) #结果: [1, 5, 9, 15]
把一个序列中的空字符串删掉,可以这么写:
def not_empty(s):
return s and s.strip()filter(not_empty, ['A', '', 'B', None, 'C', ' ']) #结果: ['A', 'B', 'C']
可见用filter()
这个高阶函数,关键在于正确实现一个“筛选”函数。
- ## python3.4中filter使用
py3与py2中filter最大的区别在于,py2中filter返回一个列表,而在py3中,filter返回一个filter类型的Iterator数据,采用惰性计算原则,只有用list(filter)才能计算出过滤列表。
0 0
- python2.7 与 python3.4 中的filter
- Python2与Python3的区别(六):filter
- Python2与python3中的编码问题
- Python2与Python3中的list异同
- python2与python3在pycharm中的切换
- python3学习笔记1:python3与Python2中的差异
- ubuntu下python2.7与python3.4共存及切换
- python3与python2.7的分别
- CentOS 7下Python2与Python3共存
- Python2.7与Python3.5的区别
- CentOS 7增加Python3与Python2共存
- python3 与 python2区别
- python2 与Python3
- map,reduce,filter之python2,python3区别
- Python2 与 Python3在串口编程中的区别
- Python2中的函数与Python3中函数的不同
- Python3中的print函数以及与python2的比较
- urllib库在python2与python3中的区别
- Source Insight 使用方法入门
- 【Linux运维入门】Jprofiler9 远程监控Linux下JBoss
- 关于排序算法的问题
- bash 中的括号
- SQL Server 2008新特性——策略管理
- python2.7 与 python3.4 中的filter
- BellMan-Ford算法--寻找最短路径
- Xcode安装插件方法(大白适用)与几个实用的插件
- UVa 819- Gifts Large and Small
- 黑白BMP文件的读写和数据黑白图像显示
- struts2生成验证码图片
- HTML5(一)HTML5表单类型与属性
- 上传图片用的复制--获取文件的前缀..
- Http方法之PUT