如何使迭代器和生成器在 micropython 中工作?

How to make iterators and generators work in micropython?

这是我的带有 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'

这似乎可行,因为对象确实被识别为 generators/iterators。那么问题是,我该如何着手进行这项工作?

很明显,MicroPython 以 Python 3 风格实现迭代器,因为 MicroPython is Python 3 implementation , rather than Python 2. What I was doing in my question is basically straight from Python 2 tutorial. However, in 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