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

请教一个关于 map 和 itertools.chain 嵌套的问题

  •  
  •   quinoa42 ·
    quinoa42 · Aug 16, 2017 · 3046 views
    This topic created in 3329 days ago, the information mentioned may be changed or developed.

    代码如下:

    import itertools
    flaten = itertools.chain.from_iterable # 方便起见
    
    def a(i):
        print("a", i)
        return list(range(i))
    def b(i):
        print("b", i)
        return "+"*i
        
    list(map(b,flaten((map(a, [1,2,3,4,5])))))
    

    在解释器下输出为:

    a 1
    b 0
    a 2
    b 0
    b 1
    a 3
    b 0
    b 1
    b 2
    a 4
    b 0
    b 1
    b 2
    b 3
    a 5
    b 0
    b 1
    b 2
    b 3
    b 4
    Out[6]:
    ['',
     '',
     '+',
     '',
     '+',
     '++',
     '',
     '+',
     '++',
     '+++',
     '',
     '+',
     '++',
     '+++',
     '++++']
    

    我之前以为会像嵌套的函数一样先执行内层再执行外层(即输出为a a a a a ... b b b b b...),结果发现似乎并非如此。我的理解为,实际上的过程似乎是在 calllist()的时候才执行。在map(b, ...)第一次调用chain对象的__next__时,chain调用了内层的map的__next__,而这又返回了a(i)的值(一个list)。而接下来的几次chain.__next__都只是从这个list中取值直到用尽,用尽后再次调用内层的map.__next__。

    请问这样的理解是否正确?

    2 replies  •  2017-08-16 15:13:13 +08:00
    guyskk
        1
    guyskk  
       Aug 16, 2017
    Python3 里面 map/range/flaten... 返回的都是生成器,不迭代它它就不会执行
    gemini
        2
    gemini  
       Aug 16, 2017
    楼上正解
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Privacy   ·   Solana   ·   917 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 24ms · UTC 18:34 · PVG 02:34 · LAX 11:34 · JFK 14:34
    ♥ Do have faith in what you're doing.