Python functions: iterators and generators
Iterators and generators are one of the key points in a function, so be sure to know what the iteration is. What is an iterator?
Preview:
Process the file, the user specifies the file and the content to find, and prints the file with each row that contains the content you want to find to the screen (using the builder)
One, iterator
650) this.width=650; "src="/img/fz.gif "alt=" Copy Code "style=" Margin:0px;padding:0px;border:none; "/>
For I in 50:print (i) #运行结果: # Traceback (most recent call last): # File "G:/python/python code/August/day2 iterator Generator/3 iterator. py", Li Ne 8, in <module># for I in 50:# TypeError: ' int ' object was not iterable
Error:
TypeError: ' int ' object is not iterable
type error: ' int ' object is not iterative, what is iteration?
iterable: an iterative or iterative;
Iterative : From the above code can be easily analyzed by the For loop value can be iterated, then we can initially summarize the type of iteration: str, list, tuple, set, Dict
Iterative--The corresponding flag has the __iter__ method
Print (' __iter__ ' in dir ([+)]) #判断一个变量是不是一个可迭代的
An iterative protocol
A requirement that can be iterated over is called an iterative protocol. The definition of an iterative protocol is very simple, which is to implement the __iter__ method internally .
Second, iterators
__iter__ Method Effect:
650) this.width=650; "id=" code_img_closed_d6878ddf-d1ca-4876-9319-b77a942964c2 "class=" code_img_closed "src="/img/ Jia.gif "style=" margin:0px;padding:0px 5px 0px 0px;border:0px;vertical-align:middle; "/> iterator
iterator: an iterator; an iterative procedure.
iterator protocol: must have __iter__ method and __next__ method
The result from ITER (x) is an iterator,
X is an object that can be iterated
In the For loop, the __next__ method is called internally to fetch a value of one.
The essence of __next__:
650) this.width=650; "id=" code_img_closed_7ce66d32-7738-4cb2-930c-80665a1c459e "class=" code_img_closed "src="/img/ Jia.gif "style=" margin:0px;padding:0px 5px 0px 0px;border:0px;vertical-align:middle; "The use of/> __next__ method
If we continue to take next to the iterator and there are no elements in it, we will get an error (throw an exception stopiteration) and tell us that there are no valid elements in the list. At this point, we're going to use the exception handling mechanism to get rid of this exception. Try_except exception handling mechanism only to understand, not the focus of this chapter, the meeting will be explained in detail.
A concise way to determine whether iterations and iterators are possible:
650) this.width=650; "id=" CODE_IMG_CLOSED_8672B255-76CD-4A76-A9CE-71EA29228FDC "class=" code_img_closed "src="/img/ Jia.gif "style=" margin:0px;padding:0px 5px 0px 0px;border:0px;vertical-align:middle; "/> judging iterations and iterators
Whether an iterator or an iterative object, you can use the For loop to traverse
Why Iterators can help you save memory
Third, generator
Iterators are mostly used inside python, and we can just use them.
What we write ourselves is called the generator, which implements the function of the iterator.
1. Generator function: General function definition, however, returns the result using the yield statement instead of the return statement. The yield statement returns one result at a time, in the middle of each result, suspends the state of the function so that the next time it leaves, it resumes execution.
2. Generator expression: Similar to list derivation, however, the generator returns an object that produces results on demand, rather than building a list of results at a time
Generator generator:
Essence: iterators (so we have the __iter__ method and the __next__ method, we do not need to implement)
Features: Lazy operation, developer customization
650) this.width=650; "id=" code_img_closed_df694af6-21b5-48b0-a7fe-9ca4184ba457 "class=" code_img_closed "src="/img/ Jia.gif "style=" margin:0px;padding:0px 5px 0px 0px;border:0px;vertical-align:middle;/> generator function
Generator benefits: Don't generate too much data in memory at once
Other applications:
650) this.width=650; "id=" code_img_closed_b33f7670-eca0-4f69-838e-b8eebb16d669 "class=" code_img_closed "src="/img/ Jia.gif "style=" margin:0px;padding:0px 5px 0px 0px;border:0px;vertical-align:middle; "/> Generator Listener File Input Example
650) this.width=650; "id=" code_img_closed_1d121a42-a92b-470c-a224-1fb69263e346 "class=" code_img_closed "src="/img/ Jia.gif "style=" margin:0px;padding:0px 5px 0px 0px;border:0px;vertical-align:middle; "/> calculate moving average simple
650) this.width=650; "id=" Code_img_closed_d2bd01ca-b72f-49ed-9019-72cec5b33e15 "class=" code_img_closed "src="/img/ Jia.gif "style=" margin:0px;padding:0px 5px 0px 0px;border:0px;vertical-align:middle; "/> Calculate moving Average upgrade _ builder activate adorner
650) this.width=650; "id=" code_img_closed_2ec65504-f2a6-497d-9335-c01fa26f35f3 "class=" code_img_closed "src="/img/ Jia.gif "style=" margin:0px;padding:0px 5px 0px 0px;border:0px;vertical-align:middle;/> yield from
Iv. list derivation and generator expressions
650) this.width=650; "id=" Code_img_closed_8202ceca-b316-4edd-aa7e-d74260f063d3 "class=" code_img_closed "src="/img/ Jia.gif "style=" margin:0px;padding:0px 5px 0px 0px;border:0px;vertical-align:middle;/> list derivation and generator expression
Advantages of using Generators:
1. Delay the calculation and return one result at a time. That is, it does not produce all the results at once, which is useful for large data processing.
2. Improve code Readability
#列表解析sum ([I for I in Range (100000000)]) #内存占用大, the machine easily dies # generator expression sum (I for I in range (100000000)) #几乎不占内存
Summarize:
1, the list of the [] resolved to () to get the generator expression
2, list parsing and generator expressions are a convenient way of programming, but the generator expression is more memory-saving
3, Python not only uses the iterator protocol, but makes the for loop become more general. Most built-in functions also access objects using an iterator protocol. For example, the SUM function is a python built-in function that accesses an object using an iterator protocol, and the generator implements an iterator protocol, so we can calculate the sum of a series of values directly
Print (sum ([2)) Print (sum (1,4)) print (SUM (x * * for X in range (4)) Print (SUM ([x * * 2 for X in range (4)])
Preview answers and mind maps to be updated tomorrow ...
Python functions: iterators and generators