Python学习基础(10):filter

filter很类似于C++里面的remove算法,它只保留符合条件的元素,并且返回的是一个iterator.实际上我也不明白它是怎么实现的….在不计算整个序列的情况下晒掉一些元素.我个人猜测是里面filter在iterator添加了限制条件,这样在计算下一个的时候将不符合条件的晒掉…..

用filter进行素数筛法

#creal all primers 
def odds():
    i = 1
    while(1):
        i += 2
        yield i

def primes(n):
    it = odds()#get all odd numbers
    yield 2
    while(n>0):
        curr_prime = next(it)#get current primes
        yield curr_prime
        it = filter(lambda x: x%curr_prime > 0,it)#lambda expression can catch the variable automatically
        n -= 1

for i in primes(100):
    print(i)

写出一个序列中的所有回数,用filter计算回数.

def is_palindorm(n):
    return str(n)[::-1] == str(n)
output = filter(is_palindorm,range(1000))
print(list(output))

你可能感兴趣的:(Python学习基础(10):filter)