python內置了一個filter函數,用於過濾序列。和map函數類似,filter()函數也接受一個函數和一個序列。只不過filter函數中是把函數依次作用於序列中的每一個元素,如果是True則保留這個元素,如果是False,則舍棄這個元素。例如,給定一個list,刪除偶數,保留奇數:
>>> def is_odd(n): ... return n % 2 ==1 ... >>> list(filter(is_odd,[1,2,3,4,5,6])) [1, 3, 5]
注意,filter返回的是一個Iterator,俗稱惰性序列,所以要使用list()函數獲得所有元素返回一個list。
用filter求素數:
素數的定義:又稱質數,為大於1的自然數中,除了1和它本身以外不再有其他因數。
計算素數的一個方法是埃氏篩法:
首先從2開始的所有自然數中:
2,3,4,5,6,7,8,9……
取序列的第一個數2,他一定是素數,然后用2把序列的倍數去掉:
3,5,7,9……
去新序列的第一個數3,他一定是素數,然后用3 把序列的3的倍數去掉:
5,7……:
5一定是素數,然后用5把序列的5的倍數去掉:
7,11……
程序如下:
>>> def odd_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 ... it = odd_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 ...
結果:
2
3
5
7
11
13
17
19
23
……
953
967
971
977
983
991
997
練習:
利用filter函數篩選出1~1000中的回數(回數是指從左往右和從右到左讀都一樣的數,例如1221,676):
>>> def is_palindrome(n): ... return n == int(str(n)[::-1]) ... >>> list(filter(is_palindrome,range(1,1000))) [1, 2, 3, 4, 5, 6, 7, 8, 9, 11, 22, 33, 44, 55, 66, 77, 88, …… 39, 949, 959, 969, 979, 989, 999]