Filter
首先了解一下这个函数,Python内建的filter()函数用于过滤序列,用法与map()函数类似,接收一个函数一个序列,不通点在filter()把传入的函数作用于每一个元素,根据返回值是true函数false,来判断元素的去留
#在一个list中只保留奇数
def is_odd(n):
return n % 2 == 1
print(list(filter(is_odd,[1,2,3,4,5,6,7,8,9,10])))
列出100以内素数
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)
for n in primes():
if n < 100:
print(n)
else:
break