博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
python生成器_Python生成器
阅读量:2532 次
发布时间:2019-05-11

本文共 5850 字,大约阅读时间需要 19 分钟。

python生成器

We will look into python generator today. In our previous lesson we have learnt about .

我们今天将研究python生成器。 在上一课中,我们学习了 。

Python生成器 (Python Generator)

Python generator is one of the most useful and special ever. We can turn a function to behave as an iterator using python generators.

Python生成器是有史以来最有用,最特殊的之一。 我们可以使用python生成器将函数转换为迭代器。

Python Generator的基本结构 (Basic Structure of Python Generator)

Basically Python generator is a function. You can consider the following as the basic structure of a python generator.

基本上,Python生成器是一个函数。 您可以将以下内容作为python生成器的基本结构。

#sample syntax of python generatordef gereratorName(argument):   #statements       yield argument   #statements#calling the generatorvariableName = gereratorName(10)print(variableName)

In the above structure you can see that everything is just like a function except one thing, that is the yield keyword. This keyword plays the vital role. Only the usage of yield, changes a normal function into a generator.

在上面的结构中,您可以看到除了一个东西(即yield关键字)外,其他所有东西都像一个函数。 此关键字起着至关重要的作用。 只有yield的用法才会将正常函数更改为生成器。

A normal function returns some value, generator yields some value. A generator automatically implements next() and _iter_.

普通函数返回一些值,生成器产生一些值。 生成器自动实现next()_iter_

Python generator is written like regular functions but use the yield statement whenever they want to return some data. Each time next() is called on the generator function, the generator resumes where it left off (it remembers all the data values and which statement was last executed).

Python生成器的编写方式与常规函数类似,但是只要它们想返回一些数据,就使用yield语句。 每次在生成器函数上调用next()时,生成器将从上次中断的地方继续(它会记住所有数据值以及上次执行的语句)。

了解Python生成器 (Understanding Python Generator)

Let’s now learn the each line of the previous code.

现在,让我们学习前面代码的每一行。

Line 2, is the declaration of the generator which takes an argument. This argument is optional. It depends on the programmer who will implement a generator.

第2行是带有参数的生成器的声明。 此参数是可选的。 这取决于实现发生器的程序员。

Line 3, 5 mentions there may be some other statements.

第3、5行提到可能还有其他一些陈述。

Line 4 is the crucial part of the above program. It says to yield the value of argument on the basis of some conditions that may be stated in the statements.

第4行是上述程序的关键部分。 它说, yield的一些条件,可能在声明中说明的基础上参数的值。

And line 8 is calling the generator with parameter 10 and line 9 prints the returned generator object. If you run the above program then it will output as following,

第8行使用参数10调用生成器,第9行显示返回的生成器对象。 如果您运行上述程序,则它将输出以下内容,

Notice that the above output is not a value. Actually it is indicating where the object is. To get the actual value you have take help of iterator. Then implicitly next() will be called on the object to get the next value that is yielded.

请注意,以上输出不是值。 实际上,它指示对象在哪里。 要获得实际值,您需要使用迭代器。 然后隐式地在对象上调用next()以获得下一个产生的值。

If you want to print the generated values without loop then you can use next() function on it. If you add one more line in the above code like below.

如果要不循环地打印生成的值,则可以在其上使用next()函数。 如果在上面的代码中再添加一行,如下所示。

print(next(variableName))

Then it will output the the value 10 which was passed as argument and yielded.

然后它将输出值10,该值作为参数传递并产生。

通过显式next()调用获取Python Generator的值 (Get Python Generator’s value with explicit next() call)

Now take a look at the following program, where we are explicitly calling the next() function of a generator.

现在看下面的程序,在这里我们显式调用生成器的next()函数。

#fruits is a generator which generates some fruit namedef fruits():   yield "Mango"   yield "Jackfruit"   yield "Banana"   yield  "Guava"#calling the generator fruitgetfruits = fruits()print(next(getfruits))print(next(getfruits))print(next(getfruits))print(next(getfruits))

In the above code, you have to know the exact number of values that were yielded. Otherwise you will get some error as no more value is generated from the generator function fruits().

在上面的代码中,您必须知道产生的值的确切数量。 否则,您将遇到一些错误,因为生成器函数fruits()不再生成任何值。

The above code will output as following:

上面的代码将输出如下:

MangoJackfruitBananaGuava

通过隐式的next()调用获取Python Generator的值 (Get Python Generator’s value with implicit next() call)

You can get the values of the generator using for loop. The following program is showing how you can print the values using for loop and generator. It will provide the same output.

您可以使用for循环获取生成器的值。 以下程序显示了如何使用for循环和generator来打印值。 它将提供相同的输出。

#fruits is a generator which generates some fruit namedef fruits():   yield "Mango"   yield "Jackfruit"   yield "Banana"   yield  "Guava"#calling the generator fruitgetfruits = fruits()for a in getfruits:   print(a)

Python Generator的工作程序 (Working Procedure of Python Generator)

Let’s now see how the generator is actually working. Normal function terminates after the return statement but generator does not.

现在让我们看看生成器实际上是如何工作的。 普通函数在return语句后终止,但生成器不终止。

For the first time we call the function it returns the first value that is yielded along with the iterator. Next time when we call the generator then it resumes from where it was paused before.

首次调用该函数时,它返回与迭代器一起产生的第一个值。 下次当我们调用生成器时,它将从之前暂停的位置恢复。

All the values are not returned at a time from a generator unlike normal function. This is the speciality of a generator. It generates the values by calling the function again and again which requires less memory when we are generating a huge number of values.

与正常功能不同,不是一次从生成器返回所有值。 这是发电机的特长。 它通过一次又一次地调用函数来生成值,这在我们生成大量值时需要较少的内存。

猜测以下Python Generator程序的输出 (Guess the output of below Python Generator Program)

Let’s see another code. If you can assume the output then it’s a gain.

让我们看看另一个代码。 如果您可以假设输出,那么它就是增益。

def timesTable(number):   for i in range(1, 11):       yield i * number       i += 1gettimes = timesTable(10)for a in gettimes:   print(a)

输出将是: (The output will be:)

Remember range() is a built-in generator which generates number within the upper bound. Hope you can now write your own generator. Best of luck.

记住range()是一个内置的生成器,它在上限内生成数字。 希望您现在可以编写自己的生成器。 祝你好运。

Reference:

参考:

翻译自:

python生成器

转载地址:http://melzd.baihongyu.com/

你可能感兴趣的文章
环形菜单的实现
查看>>
【解决Chrome浏览器和IE浏览器上传附件兼容的问题 -- Chrome关闭flash后,uploadify插件不可用的解决办法】...
查看>>
34 帧动画
查看>>
二次剩余及欧拉准则
查看>>
Centos 7 Mysql 最大连接数超了问题解决
查看>>
thymeleaf 自定义标签
查看>>
关于WordCount的作业
查看>>
C6748和音频ADC连接时候的TDM以及I2S格式问题
查看>>
UIView的layoutSubviews,initWithFrame,initWithCoder方法
查看>>
STM32+IAP方案 实现网络升级应用固件
查看>>
用74HC165读8个按键状态
查看>>
jpg转bmp(使用libjpeg)
查看>>
linear-gradient常用实现效果
查看>>
sql语言的一大类 DML 数据的操纵语言
查看>>
VMware黑屏解决方法
查看>>
JS中各种跳转解析
查看>>
JAVA 基础 / 第八课:面向对象 / JAVA类的方法与实例方法
查看>>
Ecust OJ
查看>>
P3384 【模板】树链剖分
查看>>
Thrift源码分析(二)-- 协议和编解码
查看>>