【问题标题】:How to make iterators and generators work in micropython?如何使迭代器和生成器在 micropython 中工作?
【发布时间】:2018-10-05 06:50:35
【问题描述】:

下面是我的带有 ESP8266 的 NodeMCU 板上发生的事情:

>>> x = iter((28,75,127,179))
>>> x.next()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'iterator' object has no attribute 'next'

自定义生成器也是如此:

>>> def foo():
...     for i in (28,75,127,179):
...         yield i
...         
...         
... 
>>> foo
<generator>
>>> f = foo()
>>> f.next()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'generator' object has no attribute 'next'

这似乎可行,因为对象确实被识别为生成器/迭代器。那么问题来了,我该怎么做呢?

【问题讨论】:

    标签: esp8266 nodemcu micropython


    【解决方案1】:

    显然,自 MicroPython is Python 3 implementation 以来,MicroPython 以 Python 3 风格实现迭代器,而不是 Python 2。我在问题中所做的基本上直接来自 Python 2 tutorial。但是,在Python 3 way 的事情中,这是可行的:

    >>> def foo():
    ...     while True:
    ...         for i in (28,75,127,179):
    ...             yield i
    ...             
    ...             
    ... 
    >>> f = foo()
    >>> next(f)
    28
    >>> next(f)
    75
    >>> next(f)
    127
    >>> next(f)
    179
    >>> next(f)
    28
    >>> next(f)
    75
    

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-05-16
    • 2016-09-04
    • 2020-10-16
    • 1970-01-01
    • 2020-03-10
    • 2022-11-13
    相关资源
    最近更新 更多