1. Two ways to create generator
1.1 s = (x*x for x in range (10))
This way of creating print S is:
<generator Object <genexpr> at 0x0000028b68b47888>
1.2
def f ():
Print ("OK")
Yield 1
Print ("Ok1") # Next logo
Yield 2
Print ("Ok2")
Return None
F ()
Both S and F () are an iterative object iteration.
Relative to the List Builder is the equivalent of finding a chef, but the dishes are not done. The list is to store all the elements in memory.
1.2next method
Next (s) can bring up the first element of S.
Next (f ())
Next (f ())
Next (f ()) # Print 3 OK no error receive with one variable
########################################
g = f ()
Next (g) # Print OK Ok1 ok2 and error Ok2 was printed see GA ()
Next (g)
Next (g)
Note that you want to receive it with a variable.
Def GA ():
Print ("OK")
Count = yield 1 # yield is equivalent to freezing the function next will be here then yield starts debug
Print (count)
Print ("Ok1")
Yield 2
b = GA ()
t = b.send (None) # equals next (b) but not directly send "Gaga" will error no value for you to assign value
Print (t)
B.send ("Gaga")
#jieguo: OK Gaga ok1
2. Iterator iterator
# generators are iterators (iterator) iterators that contain generators
L = [1,2,3,4] # Can iterate objects
D = ITER (l)
Print (d) # <list_iterator object at 0x0000016c2ae36c18>
# What is an iterator 1. There is ITER 2. There's next.
Print (Next (d))
########################################## #3
For i in [1,2,3,4]:
Print (i)
# What the For loop does
#1. Call the Iter method to return an iterator object
#2. Keep calling the next method of the object
#3. Handling Exception Stopiterator
From collections Import iterator,iterable
Print (Isinstance (l,list))
Print (Isinstance (d,iterator))
Iterators and generators