Python內建的filter()函數用於過濾序列。
和map()類似,filter()也接收一個函數和一個序列。和map()不同的時,filter()把傳入的函數依次作用於每個元素,然后根據返回值是True還是False決定保留還是丟棄該元素。
例如,在一個list中,刪掉偶數,只保留奇數,可以這么寫:
def is_odd(n): return n % 2 == 1 filter(is_odd, [1, 2, 4, 5, 6, 9, 10, 15]) # 結果: [1, 5, 9, 15]
把一個序列中的空字符串刪掉,可以這么寫:
def not_empty(s): return s and s.strip() filter(not_empty, ['A', '', 'B', None, 'C', ' ']) # 結果: ['A', 'B', 'C']
可見用filter()這個高階函數,關鍵在於正確實現一個“篩選”函數。
練習
請嘗試用filter()刪除1~100的素數。
思路:1,一個函數判斷n是否為素數
2,列表生成式生成1~100的素數
def is_prime(n): a=0 for i in range (2,n): if (n%i==0): a=a+1 if a==0: return True else: return False print filter(is_prime,[i for i in range(2,1001)])
