Python内建的filter()函數用于過濾序列。
和map()類似,filter()也接收一個函數和一個序列,和map()不同的是,filter把傳入的函數依次作用于每個元素,然後根據傳回值是True還是False決定保留還是丢棄該元素。(這裡順帶說一下,Python和Objective-C一樣,都是非0即真)
是以把一個序列中的非字元串和空字元串删掉,可以這麼寫:
lists = ['1', '2', '4', '5', '7', , , '', ' ', 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 =
while True:
n +=
yield n
# 然後寫一個篩選函數
def not_divisible(n):
def ax(x):
return x % n >
return ax
# return lambda x: x % n > 0
# 最後定義一個生成器,不斷傳回下一個素數
def primes():
yield
it = odd_list() #初始序列
while True:
n = next(it) #傳回序列的第一個數
yield n
it = filter(not_divisible(n), it)
for n in primes():
if n < :
print('result: ', n)
else:
break