python里的generator函数
定义一个generator函数:
#basic syntax(a function that yield) def genMul2(N): for i in range(N): yield i * 2 for i in genMul2(5):print i #inside for, the next method is called #在for循环的内部,Python调用了next方法。 #下面的x叫做generator对象 x = genMul2(2) #一直调用next方法,最后会抛出一个异常 print x print x.next() print x.next() #print x.next() !!!!error!!!!StopIteration
迭代器:
for循环、list comprehension 和 map都使用则个迭代器协议:
#iterator testDict = {'name':'Chen Zhe','gender':'male'} testIter = iter(testDict) print testIter.next() print testIter.next() #generator expressions #generator表达式 testGen = (i*2 for i in range(4)) #testGen is a generator object #testGen是一个generator对象 print testGen.next()