The iterator and generator of the 6Python All-stack Road Series

Source: Internet
Author: User

tags: Keyword Record generator capabilities

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 = 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,  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 "Eden" blog, declined reprint!

The iterator and generator of the 6Python All-stack Road Series

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.

Tags Index: