Python Yield语句似乎没有继续

2024-06-17 08:41:41 发布

您现在位置:Python中文网/ 问答频道 /正文

我一定忽略了显而易见的,但我一辈子都搞不懂为什么这个收益率语句没有不断地给我一个比上一个晚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.

Tags: 函数inimportdatetimeobjectfunction语句returns
3条回答

因为你每次都要打电话给发电机,重新启动。在

这里有一个固定版本:

dates = gettime(nextdate)
for i in range(0, 25):
    print dates.next()   # note that you're not initializing it each time here
                         # just calling next()

这给了我:

^{pr2}$

要记住的一件重要的事情是,yields实际上返回了一个生成器,当我们查看我的dates对象时可以看到:

>>> dates
<generator object gettime at 0x02A05710>

这是您可以反复调用next()以获得下一个值的内容。每次执行循环时,都会创建一个新的生成器,并从中获取下一个(在本例中是第一个)值。在

Daniel已经指出,每次通过循环都会创建一个新的生成器。与每次显式调用next()相比,循环一个生成器或让另一个生成器使用它更为常见。在

下面是如何在生成器的islice()上循环。在

from itertools import islice
import datetime

#generator 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 the_date in islice(gettime(nextdate),0,25):
    print the_date

如果需要,也可以将其简化为生成器表达式

^{pr2}$

使用打印功能:

print(*[i[0] for i in zip(gettime(nextdate), range(25))], sep='\n')

但你可能只想要一张单子。在

相关问题 更多 >