我开始学习Python,我遇到过生成器函数,其中有yield语句。我想知道这些函数最擅长解决什么类型的问题。


当前回答

缓冲。当以大块获取数据是有效的,但以小块处理数据时,生成器可能会有所帮助:

def bufferedFetch():
  while True:
     buffer = getBigChunkOfData()
     # insert some code to break on 'end of data'
     for i in buffer:    
          yield i

上面的方法可以让您轻松地将缓冲与处理分开。消费者函数现在可以一个一个地获取值,而不用担心缓冲。

其他回答

这里有一些很好的答案,但是,我也推荐完整阅读Python函数式编程教程,它有助于解释生成器的一些更有效的用例。

特别有趣的是,现在可以从生成器函数外部更新yield变量,因此可以用相对较少的工作创建动态和交织的协程。 更多信息请参见PEP 342:通过增强型生成器的协程。

现实世界中的例子

假设你的MySQL表中有1亿个域名,你想为每个域名更新Alexa排名。

你需要做的第一件事是从数据库中选择域名。

假设表名为domains,列名为domain。

如果你使用SELECT domain FROM domains,它将返回1亿行,这将消耗大量内存。所以您的服务器可能会崩溃。

所以你决定分批运行这个程序。假设我们的批量大小是1000。

在我们的第一批中,我们将查询前1000行,检查每个域的Alexa排名并更新数据库行。

在我们的第二批中,我们将处理接下来的1000行。第三批将从2001年到3000年,以此类推。

现在我们需要一个生成器函数来生成我们的批。

这是我们的生成器函数:

def ResultGenerator(cursor, batchsize=1000):
    while True:
        results = cursor.fetchmany(batchsize)
        if not results:
            break
        for result in results:
            yield result

正如你所看到的,我们的函数总是得到结果。如果使用关键字return而不是yield,那么整个函数将在到达return时结束。

return - returns only once
yield - returns multiple times

如果一个函数使用关键字yield,那么它就是一个生成器。

现在你可以这样迭代:

db = MySQLdb.connect(host="localhost", user="root", passwd="root", db="domains")
cursor = db.cursor()
cursor.execute("SELECT domain FROM domains")
for result in ResultGenerator(cursor):
    doSomethingWith(result)
db.close()

缓冲。当以大块获取数据是有效的,但以小块处理数据时,生成器可能会有所帮助:

def bufferedFetch():
  while True:
     buffer = getBigChunkOfData()
     # insert some code to break on 'end of data'
     for i in buffer:    
          yield i

上面的方法可以让您轻松地将缓冲与处理分开。消费者函数现在可以一个一个地获取值,而不用担心缓冲。

生成器提供惰性求值。你可以通过对它们进行迭代来使用它们,或者显式地使用'for',或者隐式地将它传递给任何迭代的函数或构造。您可以将生成器视为返回多个项,就像它们返回一个列表一样,但它们不是一次返回所有项,而是一个接一个地返回它们,并且生成器函数将暂停,直到请求下一个项。

生成器很适合计算大量结果集(特别是涉及循环本身的计算),因为您不知道是否需要所有结果,或者您不想同时为所有结果分配内存。或者在发电机使用另一个发电机,或者消耗其他资源的情况下,如果发生得越晚越方便。

Another use for generators (that is really the same) is to replace callbacks with iteration. In some situations you want a function to do a lot of work and occasionally report back to the caller. Traditionally you'd use a callback function for this. You pass this callback to the work-function and it would periodically call this callback. The generator approach is that the work-function (now a generator) knows nothing about the callback, and merely yields whenever it wants to report something. The caller, instead of writing a separate callback and passing that to the work-function, does all the reporting work in a little 'for' loop around the generator.

For example, say you wrote a 'filesystem search' program. You could perform the search in its entirety, collect the results and then display them one at a time. All of the results would have to be collected before you showed the first, and all of the results would be in memory at the same time. Or you could display the results while you find them, which would be more memory efficient and much friendlier towards the user. The latter could be done by passing the result-printing function to the filesystem-search function, or it could be done by just making the search function a generator and iterating over the result.

如果您想查看后两种方法的示例,请参阅os.path.walk()(带有回调的旧文件系统遍历函数)和os.walk()(新的文件系统遍历生成器)。当然,如果你真的想收集一个列表中的所有结果,生成器方法转换为大列表方法是微不足道的:

big_list = list(the_generator)

基本上避免回调函数时迭代输入维护状态。

请参阅这里和这里,了解使用生成器可以做什么。