python中yield

tech2023-05-29  104

python中yield

Thanks to Shaumik Daityari for kindly helping to peer review this article.

感谢Shaumik Daityari慷慨地帮助同行审阅本文。

When we call a function in Python, the function will normally start working until it encounters a return, exception, or reaches its end – after which it returns control back to the caller. Whenever you call that function again, the process will start from scratch!

当我们在Python中调用函数时,该函数通常会开始工作,直到遇到return , exception或到达其末尾–之后,它将控制权交还给调用者。 每当您再次调用该函数时,该过程将从头开始 !

Say that you asked a person to track the red cars on the road. The person will keep getting a question asking them if they spotted a red car or not, and the person in turn would answer with either ‘yes’ or ‘no’. If the person answered ‘yes’, the number of times the red car was spotted will increase.

假设您要一个人跟踪道路上的红色汽车。 该人将不断询问他们是否发现了红色汽车,然后该人将回答“是”或“否”。 如果此人回答“是”,发现红色汽车的次数将会增加。

Let’s see how we can do this in Python:

让我们看看如何在Python中做到这一点:

import time def red_cars(answer): n = 0 while True: if answer == 'yes': n = n + 1 return n else: return n stop = time.time() + 5 * 60 while time.time() < stop: answer = raw_input('Did you spot a red car on the road? ("yes" or "no"): ') times = red_cars(answer) print 'You have spotted ' + str(times) + ' cars so far!'

If you run the program, what do you notice? Did you notice that the number of times for the ‘yes’ answer is always capped at 1, and when you answer ‘no’ the number of times gets 0 regardless of answering ‘yes’ before?

如果您运行该程序,您会注意到什么? 您是否注意到,回答“是”的总次数始终被限制为1 ,而当您回答“否”时,无论之前是否回答“是”,该次数都变为0 ?

Here is where Python’s yield keyword comes into play. yield is a means by which we temporarily hand control to the caller, and expect to continue from the point at which control has been handed over.

这是Python的yield关键字起作用的地方。 yield是一种我们暂时将控制权移交给呼叫者并希望从控制权移交开始继续的方法。

Before giving the solution to the above example, let me demonstrate a very simple example to better illustrate how yield works.

在给出上述示例的解决方案之前,让我演示一个非常简单的示例,以更好地说明yield如何工作。

Say we have the following simple Python script:

假设我们有以下简单的Python脚本:

def step_by_step(): return 'step 1' return 'step 2' return 'step 3' step = step_by_step() for i in range (3): print step

If you run the script, you will get the following output:

如果运行脚本,将获得以下输出:

step 1 step 1 step 1

Now, if we use yield instead, as follows:

现在,如果我们改为使用yield ,则如下所示:

def step_by_step(): yield 'step 1' yield 'step 2' yield 'step 3' step = step_by_step() for i in range (3): print step.next()

The output would be as follows:

输出如下:

step 1 step 2 step 3

As you can see, we were able to create a series of values, as for each call the function continues from the point where it yields a value. This type of function is called a generator. Such function creates a generator iterator, as with each call to the method next() we move to the next yield statement.

如您所见,我们能够创建一系列值,因为对于每个调用,该函数从产生值的点继续。 这种功能称为生成器 。 该函数创建一个生成器迭代器 ,就像每次调用方法next()我们移至下一个yield语句。

If we come back to our main example (red cars), it can be written as follows to perform the required task:

如果回到主要示例(红色汽车),则可以将其编写为以下代码以执行所需的任务:

import time def red_cars(answer = None): n = 0 while True: if answer=="yes": n = n + 1 answer = yield n else: answer = yield n car_color = red_cars() car_color.next() stop = time.time() + 5 * 60 while time.time() < stop: answer = raw_input('Did you spot a red car on the road? ("yes" or "no"): ') print 'You have spotted ' + str(car_color.send(answer)) + ' cars so far!'

Thus, as we can see, yield is deemed important when we are interested in resuming execution at the last point where the function (generator) exited, and where we are also interested in keeping the values of local variables between the different calls – unlike normal functions, where such values are destroyed when exiting the function.

因此,正如我们所看到的,当我们有兴趣在函数(生成器)退出的最后一点恢复执行,并且我们也有兴趣在不同调用之间保持局部变量的值时,认为yield很重要。函数,在退出函数时销毁这些值。

There are, however, other uses of yield. For instance, you can use yield if you have a function which returns a sequence (for example, rows in an excel sheet) and you need to iterate over the sequence without having each value in memory at once. That is, to save memory.

但是, yield还有其他用途。 例如,如果您有一个返回序列的函数(例如,excel工作表中的行),并且需要遍历该序列而不必一次将每个值存储在内存中,则可以使用yield 。 即节省内存。

yield can also be used when working with iterables, where we have a large list that is difficult to pass between functions. For instance, Python’s inbuilt functions for permutations and combinations in the itertools module use yield.

在使用可迭代项时,也可以使用yield ,因为我们有大量的清单,很难在函数之间传递。 例如,Python的itertools模块中用于置换和组合的内置函数使用yield 。

翻译自: https://www.sitepoint.com/quick-tip-understanding-the-yield-keyword-in-python/

python中yield

最新回复(0)