Introduction to the usage of yield in python (with code)

不言
Release: 2019-02-22 14:49:11
forward
1906 people have browsed it

This article brings you an introduction to the usage of yield in WeChat applet python (with code). It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

First of all, if you don’t have a preliminary understanding of yield, then you first think of yield as “return”. This is intuitive. It is first of all a return. What does ordinary return mean? A certain value is returned in the program. After returning, the program will no longer run. After seeing it as return, think of it as part of a generator (the function with yield is the real iterator). Well, if you don't understand these, then treat yield as return first. Then look directly at the following program, and you will understand the full meaning of yield:

def foo():
    print("starting...")
    while True:
        res = yield 4
        print("res:",res)
g = foo()
print(next(g))
print("*"*20)
print(next(g))
Copy after login

Just a few lines of code will let you understand what yield is. The output of the code is this:

starting...
4
********************
res: None
4
Copy after login

I directly explain the code running sequence, which is equivalent to single-step debugging of the code:

1. After the program starts executing, because there is the yield keyword in the foo function, the foo function will not actually be executed. Instead, first get a generator g (equivalent to an object)

2. Until the next method is called, the foo function officially begins to execute. First execute the print method in the foo function, and then enter the while loop

3. The program encounters the yield keyword, and then thinks of yield as return. After returning a 4, the program stops and does not perform the assignment to res operation. At this time, the execution of the next(g) statement is completed, so the first part of the output The two lines (the first is the result of print above while, the second is the result of return) are the results of executing print(next(g)),

4. The program executes print(""20), output 20 *

5. Start executing the following print(next(g)) again. This time it is similar to the one above, but the difference is that this time it starts from just now The execution of the next program starts from where it stopped, that is, the assignment operation of res is to be performed. At this time, it should be noted that there is no value on the right side of the assignment operation at this time (because the return just went out, and there is no value on the left side of the assignment operation. Pass parameters), so at this time the res assignment is None, so the following output is res:None,

6. The program will continue to execute in the while, and encounter yield again. At this time, it also returns 4 , then the program stops, and the 4 output by the print function is the 4 output by this return.

At this point you may understand the relationship and difference between yield and return. The function with yield is a generator, not A function. This generator has a function which is the next function. Next is equivalent to which number is generated in the "next step". This time, the starting point of next is executed from the place where the last next stopped, so when calling next , the generator will not execute from the beginning of the foo function, it will just start where the previous step stopped, and then after encountering yield, return the number to be generated, and this step will end.

def foo():
    print("starting...")
    while True:
        res = yield 4
        print("res:",res)
g = foo()
print(next(g))
print("*"*20)
print(g.send(7))
Copy after login

Let’s look at another example of the send function of this generator. This example replaces the last line of the above example, and the output result is:

starting...
4
********************
res: 7
4
Copy after login

Let’s briefly talk about the send function. Concept: At this time, you should notice the purple words above, and why the value of res above is None, and this one becomes 7. Why? This is because send sends a parameter to res, because the above Speaking of, when returning, 4 is not assigned to res. The next time it is executed, it has to continue to perform the assignment operation and has to assign the value to None. If send is used, when the execution starts, it will continue from the previous time (return 4 After) execution, first assign 7 to res, then execute the function of next, meet the next yield, and end after returning the result.

5. The program executes g.send(7), and the program will continue to run downward from the yield keyword line, and send will assign the value 7 to the res variable

6. Because send The method contains the next() method, so the program will continue to run downwards to execute the print method, and then enter the while loop again

7. After the program execution encounters the yield keyword again, yield will return the subsequent value, the program Pause again until the next method or send method is called again.

That’s it. Let’s talk about why we use this generator. It’s because if we use List, it will take up more space. For example, take 0,1,2,3,4,5,6. ............1000

You may look like this:

for n in range(1000):
    a=n
Copy after login

At this time, range(1000) will generate a list containing 1000 numbers by default, so It takes up a lot of memory.

At this time, you can use the yield combination just now to form a generator for implementation, or you can use the xrange(1000) generator to implement

yield combination:

def foo(num):
    print("starting...")
    while num<10:
        num=num+1
        yield num
for n in foo(0):
    print(n)
Copy after login

Output:

starting...
1
2
3
4
5
6
7
8
9
10
Copy after login

xrange(1000):

for n in xrange(1000):
    a=n
Copy after login

It should be noted that there is no xrange() in python3. In python3, range() is xrange(). You can use python3 Check the type of range() in . It is already a instead of a list. After all, this needs to be optimized.

The above is the detailed content of Introduction to the usage of yield in python (with code). For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:segmentfault.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!