Python内建的filter()函数用于过滤序列。
和map()类似,filter()也接收一个函数和一个序列,和map()不同的是,filter把传入的函数依次作用于每个元素,然后根据返回值是True还是False决定保留还是丢弃该元素。(这里顺带说一下,Python和Objective-C一样,都是非0即真)
所以把一个序列中的非字符串和空字符串删掉,可以这么写:
lists = ['1', '2', '4', '5', '7', 9, 10, '', ' ', None]
def not_empty(n):
if isinstance(n, str):
return n and n.strip()
else:
return False
#注意到filter()函数返回的是一个Iterator,也就是一个惰性序列,所以要强迫filter()完成计算结果,需要用list()函数获得所有结果并返回list
print(list(filter(not_empty, lists)))
用filter求素数:
# 先写一个从3开始的无限奇数生成器
def odd_list():
n = 1
while True:
n += 2
yield n
# 然后写一个筛选函数
def not_divisible(n):
def ax(x):
return x % n > 0
return ax
# return lambda x: x % n > 0
# 最后定义一个生成器,不断返回下一个素数
def primes():
yield 2
it = odd_list() #初始序列
while True:
n = next(it) #返回序列的第一个数
yield n
it = filter(not_divisible(n), it)
for n in primes():
if n < 100:
print('result: ', n)
else:
break