Generators and iterators _python

I. Introduction generator (Generator)

Making larger data storage, if stored directly in the list, it will cause slow down enough and the speed of memory, because the list you've created is immediately created and exists, and generator (generator) in python can largely solve this problem, the generator does not create a direct start all the data, but rather a kind of "inert operation" that is created when the object is just a generator that we created, which is a record method, the data is not generated , can be used a special method, used with the check, and the generator can again traverse.

1. Create generator

 The first: Expressions

= G (X ** 2 for X in Range (1,10)) 
Print (G) # <Object Generator <genexpr> AT 0x0000022898B6C0F8>

Second: the use of a yield function is known as a generator (generator).
foo DEF (): 
Print ( 'OK1')
the yield . 1
Print ( 'OK2')
the yield 2
return None

2, where the generator
first: for looping through
for i in g:
print(i) #1 4 9
for i in foo():
print(i)

The second: s .__ next __ () method or the next (s):
Print (G .__ Next __ ()) #. 1 
Print (Next (G)) #. 4 (commonly written)
Print (G .__ Next __ ()) #. 9

. 3, the decorator send: that interaction to yield foregoing assignment interaction action (first next to go)
def foo():
print('ok1')
count=yield 1
print(count) #交互,打印123
yield 2
# return None

b=foo()
next(b)
b.send('123')

4, a simple example: Consumers producers applet

Time Import 
DEF Consumer (name):
print ( '% s prepared a bun' name%)
the while True:
Baozi # = the yield received buns do
print ( '% s came buns,% s being eaten'% (baozi , name))

DEF Producer (name):
C = Consumer ( 'a')
C2 = Consumer ( 'B')
Next (C)
Next (C2)
Print ( "% S started buns"% name)
for I in Range (10):
the time.sleep (. 1)
Print ( 'do two buns')
c.send (I) # pass buns consumers do
c2.send (i) # do consumers pass buns
producer ( 'chen') 

two, iterator
1, iterators Profile

  Iterator can remember the object is a traverse position.

  Iterator object began a visit from the first element of the collection until all the elements are accessed session is over. Iterator can only move forward not backward.

  Iterator has two basic methods: ITER ()  and  Next () .

  Strings, lists, tuples or objects can be used to create iterators.

  Builder is an iterator, the iterator is not necessarily a generator.

Guess you like

Origin www.cnblogs.com/chenxiaozan/p/12154197.html