Yield, Python keyword

Source: Internet
Author: User
Tags iterable

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 ).

 
 
  1. mylist = [1, 2, 3]   
  2.  for i in mylist :   
  3.  print(i)   

Mylist is an iterator. Whether it is using a complex expression list or directly creating a list, it is an iteratable object.

 
 
  1. mylist = [x*x for x in range(3)]   
  2. for i in mylist :   
  3. print(i)   

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:

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

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.

 
 
  1. def createGenerator() :   
  2. mylist = range(3)   
  3. for i in mylist :   
  4. yield i*i   
  5.     
  6. mygenerator = createGenerator() # create a generator   
  7. print(mygenerator) # mygenerator is an object!   
  8. <generator object createGenerator at 0xb7555c34>   
  9. for i in mygenerator:   
  10. print(i)   

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

 
 
  1. >>> Class Bank (): # create a Bank and construct an ATM
  2. ... Crisis = False
  3. ... Def create_atm (self ):
  4. ... While not self. crisis:
  5. ... Yield "$100"
  6. >>> Hsbc = Bank () # When there is no crisis, the ATM can vomit as much as you want.
  7. >>> Corner_street_atm = hsbc. create_atm ()
  8. >>> Print (corner_street_atm.next ())
  9. $100
  10. >>> Print (corner_street_atm.next ())
  11. $100
  12. >>> Print ([corner_street_atm.next () for cash in range (5)])
  13. ['$100', '$100', '$100', '$100', '$100']
  14. >>> Hsbc. crisis = True # When the crisis comes, the bank has no money
  15. >>> Print (corner_street_atm.next ())
  16. <Type 'exceptions. stopiteration'>
  17. >>> Wall_street_atm = hsbc. ceate_atm () # create an ATM and the Bank still has no money
  18. >>> Print (wall_street_atm.next ())
  19. <Type 'exceptions. stopiteration'>
  20. >>> Hsbc. crisis = False # The trouble is that even if the Bank remains empty after the crisis
  21. >>> Print (corner_street_atm.next ())
  22. <Type 'exceptions. stopiteration'>
  23. >>> Brand_new_atm = hsbc. create_atm () # construct a new ATM to restore services
  24. >>> For cash in brand_new_atm:
  25. ... Print cash
  26. $100
  27. $100
  28. $100
  29. $100
  30. $100
  31. $100
  32. $100
  33. $100
  34. $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:

 
 
  1. >>> horses = [1, 2, 3, 4]   
  2. >>> races = itertools.permutations(horses)   
  3. >>> print(races)   
  4. <itertools.permutations object at 0xb754f1dc>   
  5. >>> print(list(itertools.permutations(horses)))   
  6. [(1, 2, 3, 4),   
  7.  (1, 2, 4, 3),   
  8.  (1, 3, 2, 4),   
  9.  (1, 3, 4, 2),   
  10.  (1, 4, 2, 3),   
  11.  (1, 4, 3, 2),   
  12.  (2, 1, 3, 4),   
  13.  (2, 1, 4, 3),   
  14.  (2, 3, 1, 4),   
  15.  (2, 3, 4, 1),   
  16.  (2, 4, 1, 3),   
  17.  (2, 4, 3, 1),   
  18.  (3, 1, 2, 4),   
  19.  (3, 1, 4, 2),   
  20.  (3, 2, 1, 4),   
  21.  (3, 2, 4, 1),   
  22.  (3, 4, 1, 2),   
  23.  (3, 4, 2, 1),   
  24.  (4, 1, 2, 3),   
  25.  (4, 1, 3, 2),   
  26.  (4, 2, 1, 3),   
  27.  (4, 2, 3, 1),   
  28.  (4, 3, 1, 2),   
  29.  (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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.