【廖雪峰】函数式编程-filter

filter

filter用于过滤序列。filter也接收一个函数和一个Iterablefilter根据函数返回值的True or False来判定是否过滤掉。如果为False,就过滤掉。filter返回的也是一个惰性序列Iterator

filtermap,reduce很像很像,就是功能不同而已。

素数筛代码。

def _odd_iter():
    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) # 注意,这儿并不是作为filter参数的函数可以带参数,而是这个函数的返
        #回值是一个lambda匿名函数,这个匿名函数才是filter真正的参数。只有这样用闭包,才能每次筛选不同质数的倍数。

for n in primes():
    if n < 1000:
        print(n)
    else:
        break

猜你喜欢

转载自blog.csdn.net/weixin_41687289/article/details/81868819