-*- coding: utf-8 -*-
#Python内建的filter()函数用于过滤序列。
L=[1,2,3,4,5,6,7]
def is_odd(n):
return n%2==1
r=filter(is_odd,L)
print(list(r))
M=['A', '', 'B', None, 'C', ' ']
def empty(s):
return s and s.strip()
m=filter(empty,M)
print(list(m))
# 练习
#回数是指从左向右读和从右向左读都是一样的数,例如12321,909。请利用filter()筛选出回数:
#line = "abcde"
#line[:-1]
#结果为:'abcd'
#line = "abcde"
#line[::-1]
#结果为:'edcba'
def is_palindrome(n):
return str(n)==str(n)[::-1]
output=filter(is_palindrome,range(1,1000))
print(list(output))
def odd_iter():
n=1
while True:
n=n+2
yield n
def not_division(n):
return lambda x :x % n>0
def primes():
yield 2
it=odd_iter()
while True:
n= next(it)
yield n
it=filter(not_division(n),it)
# primes 是一个无限序列
for n in primes():
if n < 1000:
print(n)
else:
break