"The second of Python learning notes" on the yield usage of Python

Source: Internet
Author: User

In the Python keyword and its summary of "one of the Python learning notes" I mentioned yield, this article I will focus on the use of yield

It is necessary to explain the iterator (iterator) and generator (constructor) in Python before introducing yield.

One, iterator (iterator)

In Python, A For loop can be used for any type in Python, including lists, Ganso, and so on, in fact, the For loop is available for any "iterator object," which is actually an iterator

An iterator is an object that implements an iterator protocol, and the iterator protocol in Python is that an object with the next method advances to the next result, and Stopiteration is thrown at the end of a series of results. Any such object can be iterated with a for loop or other traversal tool in Python, and the iteration tool will invoke the next method at each iteration and catch the stopiteration exception to determine when to leave.

One of the obvious benefits of using iterators is that you only read one piece of data from the object at a time, without causing too much memory overhead.

For example, to read the contents of a file row by line, using the ReadLines () method, we can write:

 for  in open ("test.txt"). ReadLines ():    Print Line

This can work, but not the best way. Because he was actually loading the file into memory at once and then printing it one line at a time. This method has a large memory cost when the file is large.

Using the file iterator, we can write:

 for  in open ("test.txt"):   #usefile iterators    Print Line

This is the simplest and fastest-running notation, and he does not read the file explicitly, but instead uses the iterator to read one row at a time.

Second, generator (constructor)

The generator function is associated with the concept of an iterator protocol in Python. In short, a function that contains a yield statement is specifically compiled by the genetic builder. When the function is called, they return a generator object that supports the iterator interface. The function may have a return statement, but its purpose is to yield the value.

Unlike normal functions that generate values and exit, the generator functions automatically suspend and pause their execution and state after generating the values, and his local variables will hold state information that will be valid again when the function resumes

def g (N): ...       for inch range (N): ...              yield i **2 ...  for  in G (5): ...      print I,":"1:4: 9:16:

To understand how he works, let's take a look at the next method:

>>> t = g (5)>>> T.next () 0>>> t.next ()1>>> T.next ( )4>>> t.next ()9>>> t.next ()16>>> t.next ( ) Traceback (most Recent call last):  '<stdin>' in <module>  Stopiteration

After running 5 times next, the generator throws a Stopiteration exception, and the iteration terminates.
Let's look at a yield example and generate a Fibonacci sequence with a generator:

def Fab (max):     = 0,1     while a < Max:        yield  a        = B, a+ for  in Fab: ...      print I,","1, 1, 2, 3, 5, 8, 13,

See here should be able to understand the generator that very abstract concept of it ~ ~

"The second of Python learning notes" on the yield usage of Python

Related Article

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.