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

时间:2018-10-05 06:50:36

标签: esp8266 nodemcu 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'

这似乎可行,因为对象确实被识别为生成器/迭代器。问题是,我该如何进行这项工作?

1 个答案:

答案 0 :(得分:3)

显然,自MicroPython is Python 3 implementation起,MicroPython便以Python 3样式实现了迭代器,而不是Python2。我在做的事情基本上是直接从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