#Python内建的filter()函数用于过滤序列。
#和map()类似,filter()也接收一个函数和一个序列。和map()不同的是,
#filter()把传入的函数依次作用于每个元素,然后根据返回值是True还是False决定保留还是丢弃该元素.
#注意到filter()函数返回的是一个Iterator,也就是一个惰性序列,
#所以要强迫filter()完成计算结果,需要用list()函数获得所有结果并返回list
L = [1,2,4,89,20,21,22,32]
print(list(filter(lambda x:x%2==0,L))) # 2,4,20,22,32
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(); #1.获取奇数的序列惰性序列Iterator 3,5,7,9,11,13
while True:
n = next(it); # 3 5 7 11
yield n;
#_not_divisible(n) => 首先n赋值给n,再使用 (_not_divisible(n))(3) => 3 赋值给x
it = filter(_not_divisible(n), it);
# it = filter(lambda x: x % n > 0, it);
# => lambda表达式中的n并不等价于外面的变量n,所以这一语句执行后得不到想要的结果原因所在。
#第一次筛选掉除以3等于0的数据 =》5,7,11 13
#第二次筛选掉除以5等于0的数据 =》7,11 13
for n in primes():
if n < 1000:
print(n);
else:
break;
05-20
“相关推荐”对你有帮助么?
-
非常没帮助
-
没帮助
-
一般
-
有帮助
-
非常有帮助
提交