python高阶函数—filter

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]
原文地址:https://www.cnblogs.com/hiwuchong/p/8094924.html