In the previous chapter, we learned about iterators, which are a great tool, especially when you need to process large data sets. However, building your own iterators in Python is a bit cumbersome and time-consuming. You must define a new class that implements the iterator protocol (__iter__() and __next__() methods). In this class, you need to manage the internal state of the variables yourself and update them. In addition, when there is no value to be returned in the __next__() method, a StopIteration exception needs to be thrown.
Is there a better way to implement it? The answer is yes! This is Python’s generator solution. Let’s take a look at it.
In order to build your own iterators more efficiently, it is good to have an elegant solution for this in Python. The generator (Generator) provided by Python is used to help us easily create iterators. Generator allows you to declare a function that behaves like an iterator, that is, it can be used in a for loop. Simply put, a generator is a function that returns an iterator object. So this is also a simple way to create an iterator. When creating an iterator, you don't need to think about all the work required (like the iteration protocol and internal state, etc.) because the Generator will handle all of it.
Next, let’s go one step further and easily learn how generators work in Python and how to define them.
As mentioned in the previous section, a generator is a special type of function in Python. This function does not return a single value, but an iterator object. In a generator function, the return value uses a yield statement instead of a return statement. A simple generator function is defined below. The code list is as follows:
Code List Fragment-01
In the above list, we define a generator function . This function executes the yield statement instead of the return keyword. The yield statement makes this function a generator. When we call this function, it will return (produce) an iterator object. Let’s take a look at the generator call again:
Code List Fragment-02
Calling a generator is usually similar to creating an object, calling the generator function , and assigned to the variable.
The output of running the program is as follows:
Yielding First Item A Yielding Second Item B Yielding Last Item C
In the application generator code, we call the firstGenerator() function, which is a generator and returns an iterator object. We name this iterator myIter. Then call the next() function on this iterator object. On each next() call, the iterator executes the yield statements in their order and returns an item.
According to the rules, this generator function should not contain the return keyword. Because if it does, the return statement will terminate the function and the iterator requirements will not be satisfied.
Now, let us define a more practical generator with the help of a for loop. In this example, we will define a generator that will continuously generate a sequence of numbers starting from 0, up to a given maximum limit.
The code list is as follows:
Code list fragment-03
The output result of running the program is similar to the following:
0 1 2 3
In the above listing, we define a generator function that generates integers from 0 to a given number. As you can see, the yield statement is inside the for loop. Note that the value of n is automatically stored in successive next() calls.
One thing to note is that when defining a generator, the return value must be a yield statement. This does not mean that a return statement cannot appear in the generator. Just usually put the return statement that returns a non-None value at the end of the generator to add additional information to the StopIteration exception so that the caller can handle it. An example is as follows:
Code List Fragment-04
The following is the output result of the running program without exception handling, which is similar to the following:
99 100 Traceback (most recent call last): File "……", line 11, in <module> print(next(g)) StopIteration: 不支持大于100的数字生成!
If the program is exception-catching (try-except), the displayed results will be more concise. Try running it yourself.
如果一个函数至少包含一个yield语句,那么它就是生成器函数。如果需要,还可以包含其他yield或return语句。yield和return关键字都将从函数中返回一些东西。
return和yield关键字之间的差异对于生成器来说非常重要。return语句会完全终止函数,而yield语句会暂停函数,保存它的所有状态,然后在后续的调用中继续执行。
我们调用生成器函数的方式和调用普通函数一样。但在执行过程中,生成器在遇到yield关键字时暂停。它将迭代器流的当前值发送到调用环境,并等待下一次调用。同时,它在内部保存局部变量及其状态。
以下是生成器函数与普通函数不同的关键点:
我们用一个简单的例子来演示普通函数和生成器函数之间的区别。在这个例子中,我们要计算前n个正整数的和。为此,我们将定义一个函数,该函数给出前n个正数的列表。我们将以两种方式实现这个函数,一个普通函数和一个生成器函数。
普通函数代码如下:
代码清单片段-05
运行程序输出结果类似如下:
49999995000000 Elapsed Time in seconds: 1.2067763805389404
在代码清单中,我们定义一个普通函数,它返回前n个正整数的列表。当我们调用这个函数时,它需要一段时间来完成执行,因为它创建的列表非常庞大。它还使用了大量内存来完成此任务。
现在让我们为相同的操作定义一个生成器函数来实现,代码清单如下:
代码清单片段-06
运行程序结果类似如下:
49999995000000 (生成器模式)Elapsed Time in seconds: 1.0013225078582764
正如在生成器清单中所见,生成器在更短的时间内完成相同的任务,并且使用更少的内存资源。因为生成器是一个一个地生成项,而不是返回完整的列表。
性能改进的主要原因(当我们使用生成器时)是值的惰性生成。这种按需值生成的方式,会降低内存使用量。生成器的另一个优点是,你不需要等到所有元素都生成后才开始使用它们。
有时候,我们需要简单的生成器来执行代码中相对简单的任务。这正是生成器表达式(Generator Expression)用武之地。可以使用生成器表达式轻松地动态创建简单的生成器。
生成器表达式类似于Python中的lambda函数。但要记住,lambda是匿名函数,它允许我们动态地创建单行函数。就像lambda函数一样,生成器表达式创建的是匿名生成器函数。
生成器表达式的语法看起来像一个列表推导式。不同之处在于,我们在生成器表达式中使用圆括号而不是方括号。请看示例:
运行结果类似如下:
49999995000000 (生成器模式)Elapsed Time in seconds: 1.0013225078582764
在上述清单中,我们在生成器表达式的帮助下定义了一个简单的生成器。下面是语法:cubes_gen = (i**3 for i in nums)。你可以在输出中看到生成器对象。正如所已经知的,为了能够在生成器中获取项,我们要么显式调用next()方法,要么使用for循环遍历生成器。接下来就打印cubes_gen对象中的项:
运行程序,遍历出的元素项结果是否和列表推导式一样。
我们再看一个例子。来定义一个生成器,将字符串中的字母转换为大写字母。然后调用next()方法打印前两个字母。代码示例如下:
运行输出结果如下:
M A
生成器是非常棒的工具,特别是当需要在相对有限的内存中处理大型数据时。以下是在Python中使用生成器的一些主要好处:
1)内存效率:
假设有一个返回结果非常大序列的普通函数。例如,一个包含数百万项的列表。你必须等待这个函数完成所有的执行,并将整个列表返回给你。就时间和内存资源而言,这显然是低效的。另一方面,如果你使用生成器函数,它将一个一个地返回项,你将有机会继续执行下一行代码。而不需要等待函数执行列表中的所有项。因为生成器一次只给你一项。
2)延迟计算:
生成器提供了延迟(惰性)计算求值的功能。延迟计算是在真正需要值时计算值,而不是在实例化时计算值。假设你有一个大数据集要计算,延迟计算允许你在整个数据集仍在计算生成中可立即开始使用数据。因为如果使用生成器,则不需要整个数据集。
3)易实现和可读性:
生成器非常容易实现,并且提供了好的代码可读性。记住,如果你使用生成器,你不需要担心__iter__()和__next__()方法。你所需要的只是函数中一个简单的yield语句。
4)处理无限流:
当你需要表示无限的数据流时,生成器是非常棒的工具。例如,一个无限计数器。理论上,你不能在内存中存储无限流的,因为你无法确定存储无限流需要多少的内存大小。这是生成器真正发挥作用的地方,因为它一次只产生一项,它可以表示无限的数据流。它不需要将所有的数据流存储在内存中。
主要介绍了生成器相关知识,用于更好的自定义迭代器。内容包括何为生成器?如何自定义生成器以及和普通函数的关键区别?如何实现生成器表达式?并总结了生成器的有点。通过这篇文章,相信你能更轻松高效的掌握Python常规的生成器方方面面。
The above is the detailed content of Python programming: How to get generators and expressions? Come and dish it!. For more information, please follow other related articles on the PHP Chinese website!