Generating with the python iterator

Iterables: a realization of the object iter method is iterative

Iterator: a realization of the method and the next iter method is the object of an iterator

Builder is Iteratoran object, but list, dict, strthough Iterable(可迭代对象), is not Iterator(迭代器).

from Collections Import the Iterator   # iterator 
from Collections Import the Iterable   # iterables 
 
Print (the isinstance (S, the Iterator))      # judgment is not iterator 
Print (the isinstance (S, the Iterable))        # judgment is not iterables 
 
# to be iterative iterator object is converted to 
Print (the isinstance (ITER (S), the iterator))

Why list, dict, strand other data types are not Iterator?

This is because Python is Iteratoran object representation of the data flow , Iterator objects can be next()invoked continue to function and returns the next data until the absence of data thrown StopIterationerror. This data stream can be seen as an ordered sequence, but we can not know in advance the length of the sequence, can only continue through the next()realization of next-demand computing a data function, so the Iteratorcalculations are inert, only need to return the next data it will be calculated.

IteratorEven represent an infinite stream of data, such as all natural numbers. The list is never stored using all natural numbers.

Generator: Generator is an iterator

Create a method generators in two ways:

1. A list of the formula [] to brackets () parentheses

A = [I +. 1 for I in Range (. 5)]   # listing formula 
Print (A) 
B = (I +. 1 for I in Range (. 5))   # generator 
Print (B)   
 Print (Next (B))
 Print (Next (B))
 Print (Next (B))
 Print (Next (B))
 Print (Next (B))
 Print (Next (B)) 

output: 
[ 1, 2, 3, 4, 5 ]
 < Object Generator <genexpr> AT 0x00000163C820BAF0> 
. 1 
2 
. 3 
. 4 
. 5  
Traceback (MOST Recent Last Call):
  File "E: /myproj/pytest_demo/b.py " , Line 13 is, in <Module1>
     Print (Next (B)) 
the StopIteration 

most common generator or through the cycle calls for:
for i in b:
print(i)

2. Define a function contains statements yield, obtained by calling the function generator

DEF FIB (max): 
    n-, A, B = 0,0,1
     the while n-< max:
         the yield B 
        A, B = B, A + B 
        n- =. 1 + n-
     return  ' DONE ' 
A = FIB (. 6 ) comprises a call # functions yield statement will not be executed immediately, it just returns a builder, only when the program by next function call or traverse the generator () function will really perform
 Print (a)
 for i in fib (6 ):
    Print (i) 

output:
 <Object Generator FIB AT 0x000001866F62BAF0> 
. 1 
. 1 
2 
. 3 
. 5 
. 8 

About yield:
And return similar program execution to yield returns, and so when called again, the program to continue from the last yield Department

If you run the above principle still unclear, it may be further understood by debug example code ...

Guess you like

Origin www.cnblogs.com/wang-mengmeng/p/11440165.html