我最近在 Python 中遇到了生成器的想法,所以我为自己做了一个基本示例:
def gen(lim):
print 'This is a generator'
for elem in xrange(lim):
yield elem
yield 'still generator...'
print 'done'
x = gen
print x
x = x(10)
print x
print x.next()
print x.next()
我想知道是否有任何方法可以遍历我的变量 x
并且必须写出 print x.next()
11 次才能打印所有内容。
最佳答案
这就是首先使用生成器的全部意义:
for i in x:
print i
This is a generator 0 1 2 3 4 5 6 7 8 9 still generator... done
关于python - 了解 Python 中的迭代器和生成器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17640660/