过滤奇数:
def odd(n): return n % 2 == 1 list(filter(is_odd, [1, 2, 3,4,5,6,7,8]))
此处将filter换成map,可以看出map和filter的区别
过滤空格:
def not_empty(s):
return s and s.strip()
list(filter(not_empty, ['A', '', 'B', None, 'C', ' ']))
过滤1000以内素数:
def shengchengqi():
n = 1
while True:
n = n + 2
yield n
def shaixuanqi():
return lambda x : x % n > 0
def fanhuisushu():
yield 2
it = shengchengqi()
while True:
n = next(it)
yield n
it = filter(shaixuanqi(n),it)
for n in fanhuisushu():
if n < 1000:
print(n)
else:
break