Python学习十四:filter()
2015-06-30 21:36
405 查看
Python 中内置了filter()函数用于过滤序列。
用法:
filter()接收一个函数和一个序列。filter()把传入的函数依次作用于每个元素,然后根据返回值是True还是False决定保留还是丢弃该元素。
demo:
1、在一个list中,删掉偶数,只保留奇数:
2、把一个序列中的空字符串删掉:
学习教程:
1、廖雪峰 Python教程
用法:
filter()接收一个函数和一个序列。filter()把传入的函数依次作用于每个元素,然后根据返回值是True还是False决定保留还是丢弃该元素。
demo:
1、在一个list中,删掉偶数,只保留奇数:
#filter odd number in the list def is_odd(n): return n % 2 == 1 print filter(is_odd , [1 , 2 , 3 , 4 , 5 , 6 , 9 , 10 , 16])
2、把一个序列中的空字符串删掉:
#filter not_empty string in a list def not_empty(s): return s and s.strip() print filter(not_empty , ['A' , '' , 'B' , None , 'C',' '])
学习教程:
1、廖雪峰 Python教程
相关文章推荐
- Python图像处理(12):贝叶斯分类器
- python脚本
- Python实现决策树算法
- Python学习十三:map/reduce
- Python Decorator
- windows系统下Python环境的搭建
- Python LoggerAdpater类
- python ConfigParse模块(转)
- Python-strip()方法
- python中的元类metaclass
- Python文件操作
- Python读写文件实际操作的五大步骤
- python super()
- 用PDB库调试Python程序
- Python模块的介绍与使用
- python的keyword模块用法实例分析
- 算法导论—分治法计算最大子数组(Python)
- Python实现监控程序执行时间并将其写入日志的方法
- Python IDE pycharm
- python实现爬取千万淘宝商品的方法