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
saximi
V2EX  ›  Python

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

  •  
  •   saximi · 2017-08-09 20:14:54 +08:00 · 1533 次点击
    这是一个创建于 2462 天前的主题,其中的信息可能已经有所发展或是发生改变。
    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 条回复    2017-08-10 10:53:57 +08:00
    symons
        1
    symons  
       2017-08-09 21:07:50 +08:00
    你这 6 个 next:是在构建迭代器的时候输出的,然后最后输出的是[1, 4, 9, 16, 25]
    symons
        2
    symons  
       2017-08-09 21:13:32 +08:00
    ```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  
       2017-08-10 10:53:57 +08:00
    因为你只在__next__里 print 了'next:',没有 print self.data[self.ix]啊。。。
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   1769 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 27ms · UTC 16:34 · PVG 00:34 · LAX 09:34 · JFK 12:34
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.