V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
推荐学习书目
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 ·
    Tiande · 2015-06-25 22:34:18 +08:00 · 3646 次点击
    这是一个创建于 3225 天前的主题,其中的信息可能已经有所发展或是发生改变。

    用 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 条回复    2015-06-26 07:45:48 +08:00
    weyou
        1
    weyou  
       2015-06-25 22:43:31 +08:00   ❤️ 1
    return lambda x: x % n > 0
    是返回的一个lambda函数啊,怎么会是函数结果呢?不知道你要表达什么.
    Tiande
        2
    Tiande  
    OP
       2015-06-25 22:47:16 +08:00
    @weyou

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

    以后不能瞎猜了 ;)
    deanguqiang
        3
    deanguqiang  
       2015-06-25 23:20:36 +08:00
    Python 3 的 filter 返回的是 iterator 了?
    deanguqiang
        4
    deanguqiang  
       2015-06-25 23:27:00 +08:00
    @deanguqiang 查了一下,还真是。。。
    Tiande
        5
    Tiande  
    OP
       2015-06-25 23:48:45 +08:00
    @deanguqiang p2 p3 好可怕hhhh
    firemiles
        6
    firemiles  
       2015-06-26 07:40:04 +08:00   ❤️ 1
    @dtdnqsb 感觉python3删除了很多冗余的东西,少了很多语法糖,但函数的行为更加一致,记忆更方便。
    Tiande
        7
    Tiande  
    OP
       2015-06-26 07:45:48 +08:00 via iPhone
    @firemiles 直接学的 3,不知道以后会遇到什么坑。
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   1317 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 25ms · UTC 17:39 · PVG 01:39 · LAX 10:39 · JFK 13:39
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.