"The Road to Python Learning--Generator of Python Basics"

  A generator can be understood as a data type that automatically follows the iterable protocol . Unlike other data types, other data types need to generate an iterable object by calling the __iter__() method. That is, generators are essentially iterables. In Python, generators have two representations: generator functions and generator expressions .

Generator function:

#The generator function is basically the same as the ordinary function, the difference is that the generator function uses the yield keyword to set the return value, and multiple yields can be used in the same function 
def test_yield():
     yield 1
     yield 2
     yield 3
     yield 4

#Call the generator function and return a generator object 
test = test_yield()
 print (test)   # generator object #Through the generator object 
, you can directly call the __next__() method to get the yield return value in the function 
print (test . __next__ ())   #Get the value of the first yield - 1 print (test. __next__ ())   #Get the value of the second yield - 2 print (test. __next__ ( ))   #Get the third The value of a yield - 3 print (test. __next__ ())   #Get the value of the fourth yield - 4




#If there are other logical statements between yields, they will also be executed, that is, the program will pause when it encounters the yield keyword, and the next time it is executed, it will start to execute again from this place 
def test2_yield():
     print ( ' first ' )
     yield 1
     print ( ' second ' )
     yield 2
     print ( ' third ' )
     yield 3

#Get the generator object 
test2 = test2_yield()
 print (test2. __next__ ())   # first 1 
print (test2. __next__ ())   # second 2 
print (test2. __next__ ())   # third 3

 

Generator expression:

#Generator expression: (ternary operator) 
test = (i for i in range(5 ))
 print (test)   # generator object 
print (test. __next__ ())   # 0 
print (test. __next__ ())   # 1 
print (test. __next__ ())   # 2 
print (test. __next__ ())   # 3 
print (test. __next__ ())   # 4

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325163349&siteId=291194637