推荐学习书目
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
013231
V2EX  ›  Python

不實際運行, 你能正確回答出這段程序的輸出嗎?

  •  
  •   013231 · Sep 13, 2012 · 4003 views
    This topic created in 5028 days ago, the information mentioned may be changed or developed.
    x = [lambda: x for x in range(10)]
    print x[0]()
    x = (lambda: x for x in range(10))
    print x.next()()
    print [lambda: x for x in range(10)][0]()
    5 replies    1970-01-01 08:00:00 +08:00
    likai
        1
    likai  
       Sep 13, 2012
    这和头脑风暴上的一段代码何其相似
    fanzeyi
        2
    fanzeyi  
       Sep 13, 2012
    果不其然的做错了=.=

    答案太丑就不贴了..

    俺来解析下

    https://gist.github.com/3714157

    # 不直接贴出来了 =.=
    pyKun
        3
    pyKun  
       Oct 10, 2012
    x = [lambda: x for x in range(10)]
    这个运行看到结果了,但不明白。。。

    @fanzeyi 看你的解析也没明白。。。
    首先是个list是肯定的,你解析里的的“lambda x”是什么意思?
    013231
        4
    013231  
    OP
       Oct 10, 2012   ❤️ 1
    @pyKun
    x = [lambda: x for x in range(10)]
    x[0]就是lambda: x
    這個lambda表達式中的x引用的是哪個變量呢? 函數作用域内找不到, 就到外層作用域即全局作用域去找, 然後找到了.
    也就是說x[0]()返回的是x自身.
    pyKun
        5
    pyKun  
       Oct 10, 2012
    @013231 嗯。。明白了。。。
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   2354 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 32ms · UTC 01:27 · PVG 09:27 · LAX 18:27 · JFK 21:27
    ♥ Do have faith in what you're doing.