迭代器和生成器有什么区别? [英] What is the difference between an Iterator and a Generator?
本文介绍了迭代器和生成器有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
迭代器和生成器有什么区别?
What is the difference between an Iterator and a Generator?
推荐答案
生成器是迭代器,但不是所有的迭代器都是生成器.
Generators are iterators, but not all iterators are generators.
迭代器通常具有 next 方法来从流中获取下一个元素.生成器是与函数绑定的迭代器.
An iterator is typically something that has a next method to get the next element from a stream. A generator is an iterator that is tied to a function.
例如python中的生成器:
For example a generator in python:
def genCountingNumbers():
n = 0
while True:
yield n
n = n + 1
这样做的好处是您不需要在内存中存储无限的数字来迭代它们.
This has the advantage that you don't need to store infinite numbers in memory to iterate over them.
您可以像使用任何迭代器一样使用它:
You'd use this as you would any iterator:
for i in genCountingNumbers():
print i
if i > 20: break # Avoid infinite loop
你也可以遍历一个数组:
You could also iterate over an array:
for i in ['a', 'b', 'c']:
print i
这篇关于迭代器和生成器有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文