Python trip (five) iterators and generators

Iterator protocol

Iterative definition:

Iterative feedback process is repeated activities, its purpose is usually to approach a desired result or goal. Each repetition of the process is called an "iteration", and the results will be obtained for each iteration as the initial value for the next iteration.

 

1 iterator protocol: an object must provide the __next __ () method, the method is performed either returns the next one iteration, or to cause a StopIteration exception to terminate the iteration (forward only, not back)

2 iterables (iterator): iterator object that implements the protocol (how iterator protocol, defined inside the object the __iter __ () method

3 is a protocol convention iterables implements iterator protocol, Python internal function means (for loop, sum, min, max functions, etc.) are iterative protocol used to access the object! ! !

 

Iterator function: can save memory

 

 

 

The method iterator-related: iter ()  and  the Next () .

python built-in function next () is essentially a call to __next __ ()

List = >>> [1,2,3,4] 
>>> IT = ITER (List) # iterator object created 
>>> print (next (it)) # next element of the output iterator 
1 
>>> Print (Next (IT)) 
2 
>>>

  

 

Guess you like

Origin www.cnblogs.com/dreamer-lin/p/11588261.html