python关键字和保留字_Python中的关键字

本文深入探讨了Python中的yield关键字,解释了其如何使函数变成生成器,以及如何在循环中使用yield关键字来节省内存和时间。通过示例,文章展示了yield如何在连续调用中保持局部变量的状态。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

python关键字和保留字

When we write a function which should perform some operation and provide some result back, we generally use the return statement for returning the result.

当我们编写一个应执行某些操作并提供一些结果的函数时,通常使用return语句返回结果。

The yield keyword in python is also used to return a value from a function(just like return) but this keyword also maintains the state of the local variables of the function and when the function is called again, the execution is started from the yield statement executed last time.

python中的yield关键字还用于从函数返回值(就像return一样),但是此关键字还维护函数的局部变量的状态,当再次调用该函数时,从yield语句开始执行上次执行。

Let's see a simple example and try to understand what yield keyword actually does:

让我们看一个简单的示例,尝试了解yield关键字的实际作用:

def counter():
    x = 0
    while x < 5:
        yield x
        # incrementing the value of x
        x += 1

In the code above we have defined a simple function which has a while loop and is yielding the current value of x and then increments it.

在上面的代码中,我们定义了一个简单的函数,该函数具有while循环,并产生x的当前值,然后对其进行递增。

First things first, when we use a yield statement in a function then the function is called as Generator, about which we will learn in the next tutorial.

首先,当我们在函数中使用yield语句时,该函数称为Generator ,我们将在下一个教程中学习该函数。

A generator generates or yields values and cannot be called like a simple function rather it is called like an iterable i.e. by using a loop, for example a for loop.

生成器生成或产生值,并且不能像简单函数那样调用,而是像可迭代那样调用,即通过使用循环(例如for循环)来调用。

Let's see both the cases,

让我们看看两种情况

# calling the above function directly
print("Simple function call: ", counter())    # should print 0

# and now lets use a loop to print values
print("Now lets try using a loop:")
for y in counter():
    print(y)

Simple function call: <generator object counter at 0x7f95fba4ba98> Now lets try using a loop: 0 1 2 3 4

简单函数调用:<位于0x7f95fba4ba98的发电机对象计数器>现在让我们尝试使用循环:0 1 2 3 4

关于yield关键字要记住的几点 (Some Points to Remember about yield Keyword)

Think of yield keyword as a smart return statement which remembers what it did the last time and continues from there the next time.

yield关键字视为一个聪明的return语句,它可以记住上一次执行的操作,并在下一次从那里继续执行。

Like in the counter() function above, when we call it the first time, it will return 0, but when we call it next time, it will increment the value of x and then return 1, then we call it again, it will again increment the value of x and retun the result 2 and so on until the loop is completed.

就像上面的counter()函数一样,当我们第一次调用它时,它将返回0 ,但是当我们下次调用它时,它将递增x的值,然后返回1 ,然后再次调用它,它将再次增加x的值并重新调整结果2 ,依此类推,直到循环完成。

  1. When we use yield keyword to return data from a function it starts storing the states of the local variable as a result the overhead of memory allocation for the variable in consecutive calls is saved.

    当我们使用yield关键字从函数返回数据时,它开始存储局部变量的状态,从而节省了连续调用中变量的内存分配开销。

  2. Also, in consecutive calls the flow starts from the last yield statement executed which saves time.

    同样,在连续调用中,流程从最后执行的yield语句开始,从而节省了时间。

  3. We can easily create iterable functions using yield keyword.

    我们可以使用yield关键字轻松创建可迭代的函数。

时间来一些例子! (Time for some Examples!)

As we mentioned above, by using the yield keyword we make our function an iterable. And we know that for an iterable, we can use the next() method for iterating to the next element. So let's try to implement that in our first example.

如上所述,通过使用yield关键字,我们使函数可迭代。 而且我们知道,对于可迭代对象,我们可以使用next()方法迭代到下一个元素 。 因此,让我们尝试在第一个示例中实现它。

Example 1:

范例1:

演示地址

In the example above, we have used multiple yield statement to save the state of the execution of the function(or generator) new_gen() such that the next time that function is called the execution begins from where it last left.

在上面的示例中,我们使用了多个yield语句来保存函数(或生成器) new_gen()的执行状态,以便下次调用该函数时,从该函数的上次离开位置开始执行。

Try adding one more print(next(x)) statement to the above code and you will see the StopIteration exception which an iterator returns when there is no more data left to iterate over.

尝试在上面的代码中再添加一个print(next(x))语句,您将看到StopIteration异常,当没有更多数据可以迭代时,迭代器将返回该异常。

Example 2:

范例2:

In this code example we will be using yield keyword in a function to count the occurence of a word in a sentence.

在此代码示例中,我们将在函数中使用yield关键字来计算单词在句子中的出现。

演示地址

Using the yield keyword in above problem will help us simplify the code for searching a word in a list of words and increasing the count at the same time because yield keyword will remeber the last state and hence it will not iterate over the words which are already checked.

在上述问题中使用yield关键字将帮助我们简化用于在单词列表中搜索单词并同时增加计数的代码,因为yield关键字会记住最后一个状态,因此不会迭代已经存在的单词检查。

Similarly there are many use cases of the yield keyword. In our next tutorial we will learn about Generators which are the functions in which we use yield keyword. In the code example above, count_words is a generator.

同样, yield关键字有很多用例。 在我们的下一个教程中,我们将学习生成器 ,这些函数是我们使用yield关键字的函数。 在上面的代码示例中, count_words是一个生成器。

翻译自: https://www.studytonight.com/python/python-yield-keyword

python关键字和保留字

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值