廖雪峰[07]

filter

Python内建的filter()函数用于过滤序列。

map()类似,filter()也接收一个函数和一个序列。和map()不同的是,filter()把传入的函数依次作用于每个元素,然后根据返回值是True还是False决定保留还是丢弃该元素。

def is_odd(n):return n % 2 == 1list(filter(is_odd, [1, 2, 4, 5, 6, 9, 10, 15]))
# 结果: [1, 5, 9, 15]

filter()可以用来求素数。

def _int_iter():#生成器生成从3开始的无限奇数序列n = 1while True:n = n + 2yield ndef  _not_divisible(n):#定义筛选函数return lambda x:x % n > 0def primes():yield 2          #先返回一个2it = _int_iter() # 初始序列while True:n = next(it) # 返回序列的第一个数yield nit = filter(_not_divisible(n), it) # 构造新序列
for n in primes():#构造循环条件,使之可以输出任何范围的素数序列if n < 1000:print(n)else:break

练习

回数是指从左向右读和从右向左读都是一样的数,例如12321,909。请利用filter()筛选出回数:

# -*- coding: utf-8 -*-def is_palindrome(n):return str(n) == str(n)[::-1]  #逆序重排比较,判断回文pass# 测试:
output = filter(is_palindrome, range(1, 1000))
print('1~1000:', list(output))
if list(filter(is_palindrome, range(1, 200))) == [1, 2, 3, 4, 5, 6, 7, 8, 9, 11, 22, 33, 44, 55, 66, 77, 88, 99, 101, 111, 121, 131, 141, 151, 161, 171, 181, 191]:print('测试成功!')
else:print('测试失败!')


本文来自互联网用户投稿,文章观点仅代表作者本人,不代表本站立场,不承担相关法律责任。如若转载,请注明出处。 如若内容造成侵权/违法违规/事实不符,请点击【内容举报】进行投诉反馈!

相关文章

立即
投稿

微信公众账号

微信扫一扫加关注

返回
顶部