推荐学习书目
› Learn Python the Hard Way
Python Sites
› PyPI - Python Package Index
› http://diveintopython.org/toc/index.html
› Pocoo
值得关注的项目
› PyPy
› Celery
› Jinja2
› Read the Docs
› gevent
› pyenv
› virtualenv
› Stackless Python
› Beautiful Soup
› 结巴中文分词
› Green Unicorn
› Sentry
› Shovel
› Pyflakes
› pytest
Python 编程
› pep8 Checker
Styles
› PEP 8
› Google Python Style Guide
› Code Style from The Hitchhiker's Guide
Tiande
V2EX  ›  Python

filter(_not_divisible(n), it) 一句中,这样写:_not_divisible(n) 为什么不会报错

  •  
  •   Tiande · Jun 25, 2015 · 4435 views
    This topic created in 4112 days ago, the information mentioned may be changed or developed.

    用 filter 求素数

    ## 埃氏筛法 求 素数
    ### 从 3 开始的奇数序列
    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) # 构造新序列
    ### 测试结果
    for n in primes():
        if n < 100:
            print(n)
        else:
            break
    

    目前查到关于 filter(function, sequence) 的例子并没有这种用法:

    filter(_not_divisible(n), it)
    

    n 是 _odd_iter() 返回的一个 奇数,那 _not_divisible(n) 不就不是指向 函数,而是指向 函数的结果 了吗。

    filter 为啥还能 如丝般运行 。

    懵逼了 ;(

    求一语到破人生迷思。

    7 replies  •  2015-06-26 07:45:48 +08:00
    weyou
        1
    weyou  
       Jun 25, 2015   ❤️ 1
    return lambda x: x % n > 0
    是返回的一个lambda函数啊,怎么会是函数结果呢?不知道你要表达什么.
    Tiande
        2
    Tiande  
    OP
       Jun 25, 2015
    @weyou

    谢谢,没补到 lambda,以为返回的是结果。我再试试看。

    以后不能瞎猜了 ;)
    deanguqiang
        3
    deanguqiang  
       Jun 25, 2015
    Python 3 的 filter 返回的是 iterator 了?
    deanguqiang
        4
    deanguqiang  
       Jun 25, 2015
    @deanguqiang 查了一下,还真是。。。
    Tiande
        5
    Tiande  
    OP
       Jun 25, 2015
    @deanguqiang p2 p3 好可怕hhhh
    firemiles
        6
    firemiles  
       Jun 26, 2015   ❤️ 1
    @dtdnqsb 感觉python3删除了很多冗余的东西,少了很多语法糖,但函数的行为更加一致,记忆更方便。
    Tiande
        7
    Tiande  
    OP
       Jun 26, 2015 via iPhone
    @firemiles 直接学的 3,不知道以后会遇到什么坑。
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Privacy   ·   Solana   ·   2941 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 37ms · UTC 12:18 · PVG 20:18 · LAX 05:18 · JFK 08:18
    ♥ Do have faith in what you're doing.