构建一个基本的Python迭代器 [英] Build a Basic Python Iterator
问题描述
如何在python中创建迭代函数(或迭代器对象)?
How would one create an iterative function (or iterator object) in python?
推荐答案
python中的迭代器对象符合迭代器协议,基本上意味着它们提供两种方法: __ iter __()
和 next()
。 __ iter __
返回迭代器对象,并在循环开始时隐式调用。 next()
方法返回下一个值,并在每个循环增量处隐式调用。 next()
在没有更多值返回时引发StopIteration异常,循环结构隐式捕获该异常以停止迭代。
Iterator objects in python conform to the iterator protocol, which basically means they provide two methods: __iter__()
and next()
. The __iter__
returns the iterator object and is implicitly called at the start of loops. The next()
method returns the next value and is implicitly called at each loop increment. next()
raises a StopIteration exception when there are no more value to return, which is implicitly captured by looping constructs to stop iterating.
这是一个简单的计数器示例:
Here's a simple example of a counter:
class Counter:
def __init__(self, low, high):
self.current = low
self.high = high
def __iter__(self):
return self
def next(self): # Python 3: def __next__(self)
if self.current > self.high:
raise StopIteration
else:
self.current += 1
return self.current - 1
for c in Counter(3, 8):
print c
这将打印:
3
4
5
6
7
8
使用生成器更容易编写,如前面的答案所述:
This is easier to write using a generator, as covered in a previous answer:
def counter(low, high):
current = low
while current <= high:
yield current
current += 1
for c in counter(3, 8):
print c
打印输出将是相同的。在引擎盖下,生成器对象支持迭代器协议并执行与类Counter类似的操作。
The printed output will be the same. Under the hood, the generator object supports the iterator protocol and does something roughly similar to the class Counter.
David Mertz的文章, Iterators和Simple Generators ,是一个非常好的介绍。
David Mertz's article, Iterators and Simple Generators, is a pretty good introduction.
这篇关于构建一个基本的Python迭代器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!