filter()函式
阿新 • • 發佈:2020-12-30
高階函式——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()
>>> 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