在Python中枚举()一个生成器
我想知道当我将生成器函数的结果传递给python的枚举()时会发生什么。 例:
def veryBigHello(): i = 0 while i < 10000000: i += 1 yield "hello" numbered = enumerate(veryBigHello()) for i, word in numbered: print i, word
枚举是懒惰迭代的,还是它把所有东西都塞进了第一个呢? 我99.999%肯定它是懒惰的,所以我可以把它和发电机function完全一样,还是需要注意什么?
这很懒。 certificate情况是相当容易的:
>>> def abc(): ... letters = ['a','b','c'] ... for letter in letters: ... print letter ... yield letter ... >>> numbered = enumerate(abc()) >>> for i, word in numbered: ... print i, word ... a 0 a b 1 b c 2 c
比以前的build议更容易说明:
$ python Python 2.5.5 (r255:77872, Mar 15 2010, 00:43:13) [GCC 4.3.4 20090804 (release) 1] on cygwin Type "help", "copyright", "credits" or "license" for more information. >>> abc = (letter for letter in 'abc') >>> abc <generator object at 0x7ff29d8c> >>> numbered = enumerate(abc) >>> numbered <enumerate object at 0x7ff29e2c>
如果枚举没有执行懒惰评估,它将返回[(0,'a'), (1,'b'), (2,'c')]
或者一些(几乎)等价的。
当然,枚举实际上只是一个奇特的生成器:
def myenumerate(iterable): count = 0 for _ in iterable: yield (count, _) count += 1 for i, val in myenumerate((letter for letter in 'abc')): print i, val
既然你可以调用这个函数而不会出现内存exception,它肯定是懒惰的
def veryBigHello(): i = 0 while i < 1000000000000000000000000000: yield "hello" numbered = enumerate(veryBigHello()) for i, word in numbered: print i, word