首页 > 编程语言 > 详细

Python filter()

时间:2018-06-03 17:07:26      阅读:225      评论:0      收藏:0      [点我收藏+]

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

filter()函数返回的是一个Iterator

filter()也接收一个函数和一个序列

根据返回值是True还是False决定保留还是丢弃该元素

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)

上面的代码用filter()过滤出素数

Python filter()

原文:https://www.cnblogs.com/kwebi/p/9129547.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!