Iterators
Iteration is one of the most powerful features of Python and is a way to access the elements of a collection.
An iterator is an object that remembers where to traverse.
The iterator object is accessed from the first element of the collection until all of the elements have been accessed and finished. Iterators can only move forward without backing back.
Any object that can be used for for
the loop is a Iterable
type;
All objects that can be used for next()
functions are Iterator
types, which represent a sequence of lazy computations;
Collection data types such as list
, dict
,, and str
so on are Iterable
not Iterator
, however, you can iter()
get an object from a function Iterator
.
The Python for
loop is essentially implemented by calling next()
functions.
list=[1,2,3,4]>>> it = iter (list) # Create an Iterator object print (next (IT)) # the next element of the output iterator Print (Next (IT))2>>>
Generator
In Python, a function that uses yield is called a generator (generator).
Unlike a normal function, a generator is a function that returns an iterator that can be used only for iterative operations, and simpler to understand that the generator is an iterator.
In the process of calling the generator to run, the function pauses and saves all current run information every time the yield is encountered, returns the value of yield, and continues running from its current location the next time the next () method is executed.
Invokes a generator function that returns an Iterator object.
def fib (max): n=0 A=0 b=1 while max>N: Yield b , =b,a+b n=n+1F=fib (Ten) for in F: print(i)
Decorative Device
Adorner: The essence is a function, used to decorate other functions, attaching some functions that are not in themselves
Principle: 1. Cannot modify the source code of the decorated function
 2. Cannot modify the calling method of the decorated function
import time def bar (): Time.sleep ( 3 print (" in the bar " ) def Span style= "COLOR: #000000" > Test1 (func): start_time =time.time () func () # run bar stop_time=time.time () print (" the func run time is%s "% (Stop_time-start_time)") test1 (bar) bar ()
Four. Python iterator builder and adorner