Detailed method of yield return generator in Python

  • 2021-12-12 04:48:41
  • OfStack

Catalog 1. Iterator 2. Generator 3. yield1. Example 12. Summary of Example 2

In the simplest and intuitive understanding, yield is treated as return, except that return returns 1 value and yield returns 1 generator.

To understand the role of yield, you must understand what a generator is.

Before you can understand the generator, you must first understand the iterator.

1. Iterators

Read the list item by item, which is called iteration.


mylist = [1, 2, 3]
for i in mylist: #  Iterable object 
    print(i)

The list parser is also an iterator.


mylist = [x*x for x in range(3)]
for i in mylist:
    print(i)
'''
0
1
4
'''

All for... in... are iterators, including lists, strings, files, and so on.

However, all the values of the iterator are stored in memory, which wastes 10 points of memory.

Therefore, there is the concept of generator.

2. Generator

A generator is a kind of iterator, which can only iterate once.

The generator does not store all values at once, but generates values dynamically.


mygenerator = (x*x for x in range(3))
for i in mygenerator:
    print(i)

The generator can only be executed once, and nothing will be output when it is executed again.

3. yield

1. Example 1

yield is similar to the return keyword, except that the function returns 1 generator.


#  Create a generator 
def createGenerator():
    mylist = range(10)
    for i in mylist:
        print(i) #  Verify that the function is called without executing 
        yield i*i
mygenerator = createGenerator()    
print(mygenerator) 
# <generator object createGenerator at 0x0000029E88FDCA50>
#  Use the generator 
for i in mygenerator:
    print(i)
#  Execute again   Returns null   There is no value 

The function will return a set of values that only need to be read once, which can greatly improve code performance.

When a function is called, the code in the function body does not execute, and the function returns only the generator object.

Every time the code continues from where it stopped when using the generator.

2. Example 2


#Python Learning and communication group: 531509025
#  Learn another 1 Examples 
def foo():
    print("starting...")
    while True:
        res = yield 4 #  Function does not really execute 
        print("res:", res)
g = foo() #  Get 1 Generator objects 
print(next(g)) #  Real implementation 
print("*"*20)
print(next(g)) #  From above 1 Continue execution where it stopped for the second time 
'''
starting...
4
********************
res: None
4
'''
print(g.send(7))

After yield is executed, the while loop will jump out.

The next function is used to perform the next step.

The send function is used to send 1 argument to the generator. And the send method includes the next method.

Summarize

This article is here, I hope to give you help, but also hope that you can pay more attention to this site more content!


Related articles: