python生成器_Python生成器

python生成器

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

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

Python生成器 (Python Generator)

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

Python生成器是有史以来最有用,最特殊的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 generator
def gereratorName(argument):
   #statements
       yield argument
   #statements


#calling the generator
variableName = 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行显示返回的生成器对象。 如果您运行上述程序,则它将输出以下内容,

<generator object gereratorName at 0x1019d6f10>

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 name
def fruits():
   yield "Mango"
   yield "Jackfruit"
   yield "Banana"
   yield  "Guava"


#calling the generator fruit
getfruits = 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:

上面的代码将输出如下:

Mango
Jackfruit
Banana
Guava

通过隐式的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 name
def fruits():
   yield "Mango"
   yield "Jackfruit"
   yield "Banana"
   yield  "Guava"
#calling the generator fruit
getfruits = 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 += 1

gettimes = 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 API Doc

参考: Python API文档

翻译自: https://www.journaldev.com/14954/python-generator

python生成器

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值