python based learning - iterators & Generator

First, iterators

  1, the iterator concept

  1.1 iterator protocol: refers to the object must provide a next method, the method is performed either next iteration of Lake Van, or to cause abnormalities of a stopIteration to terminate the iteration ( only next to go forward not back )

  1.2 iterables: an object that implements the iterator protocol. Iteration: popular talk is a process of renewal

  1.3 protocol is a convention, iterables implements iterator protocol, Python an internal tool (for loop, min functions, sum and the like) using an iterative protocol to access the object.

  2, for circulation mechanism, it is based on the work of the iterator protocol

  Data Types 2.1 for traversal loop:

    1) Ordered Type: strings, lists and tuples

    2) type of disorder: dictionaries, collections and documents

  2.2 for loop works

    1) first to be traversed data objects accumulated inside _ilter_ call center method, converted into iterative

    After 2) to help find the roar of abnormal termination

  Summary: For loop is to provide a unified method for all objects can traverse iterator-based protocol

  3, Sample

= l [1,3,2 ]
 for I in l: # put into a list l of cocoa iteration object, it follows an iterative protocol, and then for an iterative loop to loop through the protocol to 
    Print (I) 

iter_l = l . __iter__ ()
 Print (. iter_l __next__ ()) 

# Second way: built-in functions next, next method is to call the iterator iter_l .__ next __ () this method itself
l=[1,3,2]
iter_l path = i .__ __ ()
print(next(iter_l))
DIC = { " A " :. 1, " B " : 22 is } 
iter_d = DIC. the __iter__ ()
 Print (iter_d. __next__ ())
 Print (iter_d. __next__ ()) # _next_ () method execution result is the key value 

# Second way: 
for i in dic:
     Print (i)

Second, the generator

  1) automatically iterator protocol itself iterables, delay calculation save memory

  2) a list of parsed [] with () generator expression is obtained

  3) list comprehensions and generator expressions are a convenient way of programming, generator expressions under relatively more economical memory

  4) Python in the loop for the iterator protocol based on job completion

  1, ternary expression & list comprehension

= name " the CC " 
RES = " Xiaozhan "  IF name == " the CC "  the else  " green " # ternary expressions with 
Print (RES) 

# Second way 
L = [ " egg S% ' % I for I in Range (10 ) IF I>. 5 ] # list analyzing
 Print (L) 

# results: [ 'eggs 6', '7 egg', 'eggs 8', '9 eggs']

  2, generator expression

L = ( " egg% S " % I for I in Range (10) IF I>. 5 )
 Print (L)
 Print (L. __next__ ())
 Print (Next (L)) 

# Results: 
<Generator Object <genexpr> at 0x00000243BFCD9258> 
eggs 6 
eggs 7

  3, the function generator

   Generator benefits: 1) yield the equivalent of return, as a return value for

         2) function to retain operating state, from one end position to continue to run the next

  3.1 Sample

Import Time
 DEF Test (): 
    the time.sleep ( . 3 )
     yield . 1   # each yield is equivalent to a return returns 
    yield 2
     Print ( " starting now " )
     yield . 3 
RES = Test () # get generator
 Print (RES)   # generating object 
Print (RES. __next__ ()) # generator operating yield1 
Print (RES. __next__ ()) # generator operating yield2 
Print (RES. __next__ ()) # generator operating yield3

 

Import Time
 DEF the Test ():
     Print ( " start it " )
     yield  , " I " 
    the time.sleep ( 3 )
     Print ( " two began Rights " )
     yield  " she " 
    the time.sleep ( 3 )
     Print ( " three friends began " )
     yield  " his " 
RES = the Test ()
 Print (RES)   # generator object 
Print (RES. __next__()) # Run my generator yield 
Print (RES. __Next__ ()) # run the generator yield her 
Print (RES. __Next__ ()) # run the generator yield him
DEF prduct_baozi ():
     for I in Range (100 ):
         Print ( " Start steamed buns friends " )
         the yield  " steamed a drawer% S " % I
         Print ( " start selling buns " ) 
Pro1 = prduct_baozi () 
Baozi = Pro1 . __next__ () 
Baozi = Pro1. __next__ () 
Baozi = Pro1. __next__ () 
Baozi = Pro1. __next__ ()

   3.2send stay a function of position, send the value is assigned to the rest position

DEF Test ():
     Print ( " starting now " ) 
    First = the yield 
    Print ( " first " , First)
     the yield 2
     Print ( " second " ) 
T = Test () 
RES = T. __next__ ()
 Print (RES ) 
RES = t.send ( " function that remain in the first position, my first assignment is to give " )
 Print (RES)

  3.2 Producers consumer model (single-threaded concurrency)

# A process: two bun
Time Import 
DEF Custmer (name):
Print ( "I [% s], I am prepared a bun"% name)
the while True:
Baozi = yield
the time.sleep (1)
Print ( "% S very happy to [% s] ate "% (name, Baozi))
C1 = Custmer (" the CC ")
C2 = Custmer (" Nana ")
C1 .__ Next __ ()
C2 .__ Next __ ()
c1.send (" bun ")
C2. send ( "bun")
# process II: the use of automatic baking function
Time Import 
DEF Custmer (name):
Print ( "I [% s], I am prepared a bun"% name)
the while True:
Baozi = yield
the time.sleep (1)
Print ( "% S very happy to [% s] ate "% (name, Baozi))
DEF productor ():
C1 = Custmer (" the CC ")
C2 = Custmer (" Nana ")
C1 .__ Next __ ()
C2 .__ Next __ ()
c1.send (" buns ")
c2.send (" bun ")
productor ()
# process III: creating multiple buns for loop
Import Time
 DEF Custmer (name):
     Print ( " I [% s], I am prepared a bun " % name)
     the while True: 
        Baozi = yield 
        the time.sleep ( 1 )
         Print ( " % S very happy to [% s] ate " % (name, Baozi))
 DEF productor (): 
    C1 = Custmer ( " the CC " ) 
    C2 = Custmer ( " Nana " ) 
    C1. __next__ () 
    C2. __next__()
    for i in range(10):
        time.sleep(1)
        c1.send("包子%s" %i)
        c2.send("包子%s" % i)
productor()

 

Guess you like

Origin www.cnblogs.com/xucuiqing/p/11723661.html