The iterator and generator of the 6Python All-Stack Road series

Source: Internet
Author: User
Tags generator

Generator

Just having the ability to generate something, if not __next__ used, is not worth the gain.

Create a generator function

>>> def SCQ (): ... print ("11") # when the yield keyword is encountered in a function code block, this function is a generator function ... yield 1 ...    Print ("+") ... yield 2 ... Print ("+") ... yield 3 ...

Assign the generator to an object

>>> r = SCQ ()

View the Su type of R and output R value

>>> print (Type (r), R) <class  ' generator ' >&NBSP;<GENERATOR&NBSP;OBJECT&NBSP;SCQ  at 0x000001f117d8df10> 

__next__ , the code executes in order, when executed to yield is returned and presented, yield is the return value, and the location where the code executes is recorded and exits

>>> ret = r.__next__ () 11

The execution of the second execution will continue at the same location as the last code execution.

>>> ret = r.__next__ () 22>>> ret = r.__next__ () 33

__next__ gets stopiteration Error

>>> ret = r.__next__ () Traceback (most recent call last): File "<stdin>", line 1, in <module>stopiter ation

Create a similar xrange feature with the generator

Code

#  creates a generator function, the function name is Range,n is an incoming parameter, and is the maximum value of the number of outputs Def range (n):    #  default starting from 0      start = 0    #  Enter the while loop, and if the minimum value is less than the maximum, enter the loop      while start < n:        #  The first time you return to start, the following code does not execute         yield start         #  the second time in the start = start + 1, and then into the next cycle          start += 1        #  Stop parameter is 5obj  = range (5) #  The first number is assigned to N1N1&NBSP;=&NBSP;OBJ.__NEXT__ () #  The second number is assigned to N2N2&NBSP;=&NBSP;OBJ.__NEXT__ ( ) #  the third number assignment to n3n3 = obj.__next__ () #  fourth number assignment to n4n4 = obj.__next__ () #  fifth number assigned to N5N5  = obj.__next__ () #  Output The value of this five-digit print (N1,N2,N3,N4,N5)

Execution results

C:\Python35\python.exe f:/python_code/sublime/week5/day03/s1.py0 1 2 3 4Process finished with exit code 0
Iterators

With the ability to access the generator, you can access the value of the generator, similar to the method of the generator, a value that is __next__ worth iterating, and can only be searched in order.

Characteristics:

    1. The visitor does not need to care about the structure inside the iterator, but simply continues to fetch the next content through the next () method

    2. A value in the collection cannot be accessed randomly, and can only be accessed from beginning to end

    3. You can't go back halfway through the interview.

    4. Facilitates recycling of large data sets, saving memory

optimization above range or xrange 's generator

Def irange (start, stop, step=1):     while start != stop:         yield start         start += step    else:         Raise stopiteration        for n in irange (1, &NBSP;10):     "" For Loop will stop "" "If you encounter Stopiteration     print (n)      ret = irange (1, 20) print (ret)   #  returns a generator that is equivalent to creating only one value in memory print (list ( RET)   #  If you want to get all the values, you can change to a list
/library/frameworks/python.framework/versions/3.5/bin/python3.5/users/ansheng/mypythoncode/hello.py123456789 <generator object Irange at 0x1021df7d8>[1, 2, 3, 4, 5, 6, 7, 8, 9, ten, one, one,,, 19]process F Inished with exit code 0

#Python全栈之路 #迭代器 #生成器


This article is from the "Eden" blog, so be sure to keep this source http://edeny.blog.51cto.com/10733491/1916738

The iterator and generator of the 6Python All-Stack Road series

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.