我一定忽略了显而易见的,但我一辈子都搞不懂为什么这个收益率语句没有不断地给我一个比上一个晚15分钟的新的datetime值。gettime函数的行为更像是一个“returns”而不是“yields”的函数。在
import datetime
#function that continually adds 15 minutes to a datetime object
def gettime(caldate):
while True:
yield caldate
caldate += datetime.timedelta(minutes=15)
#initialize a datetime object
nextdate = datetime.datetime(2011, 8, 22, 11,0,0,0)
#call gettime function 25 times.
for i in range(0,25):
print gettime(nextdate).next()
#output feels like it should be a series of incrementing datetime values 15 minutes apart.
#in actuality, the same result namely:
#2011-08-22 11:00:00
#happens 25 times.
因为你每次都要打电话给发电机,重新启动。在
这里有一个固定版本:
这给了我:
^{pr2}$要记住的一件重要的事情是,
yield
s实际上返回了一个生成器,当我们查看我的dates
对象时可以看到:这是您可以反复调用
next()
以获得下一个值的内容。每次执行循环时,都会创建一个新的生成器,并从中获取下一个(在本例中是第一个)值。在Daniel已经指出,每次通过循环都会创建一个新的生成器。与每次显式调用
next()
相比,循环一个生成器或让另一个生成器使用它更为常见。在下面是如何在生成器的islice()上循环。在
如果需要,也可以将其简化为生成器表达式
^{pr2}$使用打印功能:
但你可能只想要一张单子。在
相关问题 更多 >
编程相关推荐