Iterator)
To understand what yield is, first understand what the generator is. before talking about the generator, first talk about the iterator. When creating a list, you can read each item one by one, which is called iteration ).
- mylist = [1, 2, 3]
- for i in mylist :
- print(i)
- 1
- 2
- 3
Mylist is an iterator. Whether it is using a complex expression list or directly creating a list, it is an iteratable object.
- mylist = [x*x for x in range(3)]
- for i in mylist :
- print(i)
- 0
- 1
- 4
You can use "for... in..." to operate iteratable objects, such as list, string, and files. These iteration objects are very convenient for us to use, because you can read data repeatedly as you wish. But you have to store all the elements in the memory in advance. When there are many elements in those objects, not every item is useful to you.
Generators)
The generator is also an iteratable object, but you can only read it once, because it does not store all values in the memory, and it dynamically generates values:
- mygenerator = (x*x for x in range(3))
- for i in mygenerator :
- print(i)
- 0
- 1
- 4
The use of () and [] results is the same, but the second execution of "for in mygenerator" won't have any results returned, because it can only be used once. Calculate 0 first, then 1, then 4, and so on.
Yield
Yield is a keyword. It is used like return. yield is telling the program that the function is required to return a generator.
- def createGenerator() :
- mylist = range(3)
- for i in mylist :
- yield i*i
-
- mygenerator = createGenerator() # create a generator
- print(mygenerator) # mygenerator is an object!
- <generator object createGenerator at 0xb7555c34>
- for i in mygenerator:
- print(i)
- 0
- 1
- 4
This example is meaningless, but it clearly indicates that the function will return a set of values that can only be read once. To master yield, you must first understand: when you call the generator function, the createGenerator () in the above example does not execute the code in the function body. It only returns the generator object. This method is quite subtle. The code in the function body runs only when the for generator is cyclically iterated.
When a function is run for the first time, it will return the first value of the loop from the beginning of the function until yield is met. Then, the interactive operation and return until no value is returned. If the function is running but does not encounter yield, it is considered that the generator is null because the loop is terminated or it does not meet any "if/else" conditions ".
Next, read a short piece of code to understand the advantages of the generator:
Control generator exhaustive
- >>> Class Bank (): # create a Bank and construct an ATM
- ... Crisis = False
- ... Def create_atm (self ):
- ... While not self. crisis:
- ... Yield "$100"
- >>> Hsbc = Bank () # When there is no crisis, the ATM can vomit as much as you want.
- >>> Corner_street_atm = hsbc. create_atm ()
- >>> Print (corner_street_atm.next ())
- $100
- >>> Print (corner_street_atm.next ())
- $100
- >>> Print ([corner_street_atm.next () for cash in range (5)])
- ['$100', '$100', '$100', '$100', '$100']
- >>> Hsbc. crisis = True # When the crisis comes, the bank has no money
- >>> Print (corner_street_atm.next ())
- <Type 'exceptions. stopiteration'>
- >>> Wall_street_atm = hsbc. ceate_atm () # create an ATM and the Bank still has no money
- >>> Print (wall_street_atm.next ())
- <Type 'exceptions. stopiteration'>
- >>> Hsbc. crisis = False # The trouble is that even if the Bank remains empty after the crisis
- >>> Print (corner_street_atm.next ())
- <Type 'exceptions. stopiteration'>
- >>> Brand_new_atm = hsbc. create_atm () # construct a new ATM to restore services
- >>> For cash in brand_new_atm:
- ... Print cash
- $100
- $100
- $100
- $100
- $100
- $100
- $100
- $100
- $100
The generator is very useful for resource access control.
Iteration tools, your best friend
The iteration tool module contains the specified functions used to operate the iterator. Want to copy an iterator? Link two iterators? With one liner, one-liner only requires one line of code to handle the task.) use an embedded list to combine a set of values? Do not use list to create Map/Zip? · What you need to do is import itertools. For example:
All possibilities for a four-horse race to reach the destination:
- >>> horses = [1, 2, 3, 4]
- >>> races = itertools.permutations(horses)
- >>> print(races)
- <itertools.permutations object at 0xb754f1dc>
- >>> print(list(itertools.permutations(horses)))
- [(1, 2, 3, 4),
- (1, 2, 4, 3),
- (1, 3, 2, 4),
- (1, 3, 4, 2),
- (1, 4, 2, 3),
- (1, 4, 3, 2),
- (2, 1, 3, 4),
- (2, 1, 4, 3),
- (2, 3, 1, 4),
- (2, 3, 4, 1),
- (2, 4, 1, 3),
- (2, 4, 3, 1),
- (3, 1, 2, 4),
- (3, 1, 4, 2),
- (3, 2, 1, 4),
- (3, 2, 4, 1),
- (3, 4, 1, 2),
- (3, 4, 2, 1),
- (4, 1, 2, 3),
- (4, 1, 3, 2),
- (4, 2, 1, 3),
- (4, 2, 3, 1),
- (4, 3, 1, 2),
- (4, 3, 2, 1)]
Understand the internal mechanism of iteration:
Iteration is an iterables object that implements the _ iter _ () method and iterators, and implements the _ next _ () method). An iteratable object is any object that can return an iterator. An iterator is an object that is iterated by an application in an iteration object. In other words, the following is an example: the _ iter _ () method of the iterable object can return the iterator object. iterator obtains each value by calling the next () method ), you can use the Iterable interface in Java APIs to compare it with the Iterator interface.
The Python yield keyword explained