filter()函数
⾼阶函数——filter()
1.  filter()函数⽤于过滤序列,作⽤是从⼀个序列中筛选出符合条件的元素。
2.  filter()把传⼊的函数⼀依次作⽤于每个元素,然后根据返回值是 True 还是 False 来判断是否留下该元素。
3.  filter()函数第⼀个参数接收⼀个函数,第⼆个参数接收⼀个序列。
4.  filter()函数返回的是⼀个 Iterator,也就是⼀个惰性序列,所以只有在取 filter()结果的时候,才能真正的筛选并每次返回下⼀个筛选出的元素。
例如,选出⼀个序列中的奇数:
>>> def is_odd(n):
return n%2==1
>>> f=filter(is_odd,[1,2,3,4,5,6,7,8,9,10])
>>> f
<filter object at 0x00000233C46F2670>
#filter()函数返回的是⼀个惰性序列,所以要强迫filter()完成计算结果,需要⽤list()函数获得所有结果并返回list >>> list(f)
[1, 3, 5, 7, 9]
把⼀个序列中的空字符串删掉:
>>> def not_empty(s):
return s and s.strip()
字符串函数strip()的作用是
>>> list(filter(not_empty,['a','','b',None,'c',' ']))
['a', 'b', 'c']
5.  ⽤ filter()求素数
埃⽒筛法:
def _int_iter():#⽣成器⽣成从3开始的⽆限奇数序列
n = 1
while True:
n = n + 2
yield n
def  _not_divisible(n):#定义筛选函数
return lambda x:x % n > 0
def primes():
yield 2          #先返回⼀个2
it = _int_iter() # 初始序列
while True:
n = next(it) # 返回序列的第⼀个数
yield n
it = filter(_not_divisible(n), it) # 构造新序列
for n in primes():#构造循环条件,使之可以输出任何范围的素数序列    if n < 1000:
print(n)
else:
break

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。