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

请教一个关于列表解析的问题

  •  
  •   saximi · Aug 9, 2017 · 2083 views
    This topic created in 3286 days ago, the information mentioned may be changed or developed.
    class Iters:
    def __init__(self, value):
    self.data = value

    def __iter__(self):
    print('iter=>', end='')
    self.ix = 0
    return self

    def __next__(self):
    print( 'next:', end=' ')
    if self.ix== len(self.data): raise StopIteration
    item = self.data[self.ix]
    self.ix += 1
    return item


    X = Iters([1, 2, 3, 4, 5])
    print([i ** 2 for i in X])

    上面代码输出如下:
    iter=>next: next: next: next: next: next: [1, 4, 9, 16, 25]

    我的问题是,为何输出是连着 6 个“ next: ”然后才是列表,而不是形如“ next: 1 ”这种在“ next: ”后紧跟数字的方式?
    谢谢
    3 replies    2017-08-10 10:53:57 +08:00
    symons
        1
    symons  
       Aug 9, 2017
    你这 6 个 next:是在构建迭代器的时候输出的,然后最后输出的是[1, 4, 9, 16, 25]
    symons
        2
    symons  
       Aug 9, 2017
    ```python
    class Iters:
    def __init__(self, value):
    self.data = value

    def __iter__(self):
    print('iter=>', end='')
    self.ix = 0
    return self

    def __next__(self):
    print( 'next:', end=' ')
    if self.ix== len(self.data): raise StopIteration
    item = self.data[self.ix]
    self.ix += 1
    return item


    X = Iters([1, 2, 3, 4, 5])
    heihei = ([i ** 2 for i in X])

    print ('\n====================')

    print (heihei)

    ```

    [symons@symons_laptop symons]$ python haha.py
    iter=>next: next: next: next: next: next:
    ====================
    [1, 4, 9, 16, 25]

    看这个代码和运行结果就知道啦
    jmc891205
        3
    jmc891205  
       Aug 10, 2017
    因为你只在__next__里 print 了'next:',没有 print self.data[self.ix]啊。。。
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   877 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 25ms · UTC 22:31 · PVG 06:31 · LAX 15:31 · JFK 18:31
    ♥ Do have faith in what you're doing.