python之高阶函数filter
2018-07-23 10:59
204 查看
Python内建的
filter()函数用于过滤序列。
和
map()类似,
filter()也接收一个函数和一个序列。和
map()不同的是,
filter()把传入的函数依次作用于每个元素,然后根据返回值是
True还是
False决定保留还是丢弃该元素。
例如,在一个list中,删掉偶数,只保留奇数,可以这么写:
def is_odd(n): return n % 2 == 1 list(filter(is_odd, [1, 2, 4, 5, 6, 9, 10, 15])) # 结果: [1, 5, 9, 15]
把一个序列中的空字符串删掉,可以这么写:
def not_empty(s): return s and s.strip() list(filter(not_empty, ['A', '', 'B', None, 'C', ' '])) # 结果: ['A', 'B', 'C']
可见用
filter()这个高阶函数,关键在于正确实现一个“筛选”函数。
注意到
filter()函数返回的是一个
Iterator,也就是一个惰性序列,所以要强迫
filter()完成计算结果,需要用
list()函数获得所有结果并返回list。
来个难一点的
用filter求素数
首先,列出从
2开始的所有自然数,构造一个序列:
2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, ...
取序列的第一个数
2,它一定是素数,然后用
2把序列的
2的倍数筛掉:
3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, ...
取新序列的第一个数
3,它一定是素数,然后用
3把序列的
3的倍数筛掉:
5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, ...
取新序列的第一个数
5,然后用
5把序列的
5的倍数筛掉:
7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, ...
不断筛下去,就可以得到所有的素数。
用Python来实现这个算法,可以先构造一个从
3开始的奇数序列:
def _odd_iter(): n = 1 while True: n = n + 2 yield n
注意这是一个生成器,并且是一个无限序列。 然后定义一个筛选函数:
def _not_divisible(n): return lambda x: x % n > 0
最后,定义一个生成器,不断返回下一个素数:
def primes(): yield 2 it = _odd_iter() # 初始序列 while True: n = next(it) # 返回序列的第一个数 yield n it = filter(_not_divisible(n), it) # 构造新序列
这个生成器先返回第一个素数
2,然后,利用
filter()不断产生筛选后的新的序列。
由于
primes()也是一个无限序列,所以调用时需要设置一个退出循环的条件:
# 打印1000以内的素数: for n in primes(): if n < 1000: print(n) else: break
相关文章推荐
- python函数式编程内建函数filter,map,reduce函数
- python中filter()函数
- Python---filter()函数
- Python 内置模块函数filter reduce
- Python中reduce、map、filter、apply、tuple函数
- [Python] 函数lambda(), filter(), map(), reduce()
- python的几个内建函数:apply,filter,map,reduce
- python中map、reduce、filter、自定义排序函数、装饰器函数和偏函数
- Python内建函数之——filter,map,reduce
- Python入门 第四天(函数式编程、map、reduce、filter、排序函数、函数返回函数、闭包、匿名函数lambda)
- python中的map(),reduce(),filter()函数
- python: filter 函数
- python常用函数之lambda、reduce、map、sorted、filter
- Python filter()函数
- Python之map(),reduce(),filter()函数
- python函数—filter,map,keys
- python 常用函数 filter
- Python 第三篇(上):python文件基础操作、json模块、lambda、map、filter、reduce和函数位置参数
- Python 内建函数 - filter(function, iterable)
- Python中lambda(),filter(),map()函数