1. List-Generated
1 for in range [2 ]in range (10)]
2. Generator
1 #Author Qian Chenglong2 3 #List Builder4A= (i*2 forIinchRange (10))5 #A[1] #只是将算法存储了, the corresponding data is generated only at the time of the call and cannot be read directly6A.__next__()#the generator can only be pulled back one at a-and only the current value is stored7 8 #function Builder9 Ten #def fib (max): One #n,a,b = 0,0,1 A #While N < max: - #print (b) - #A, B = b,a+b the #n + = 1 - #return ' Done ' - - #to turn the FIB function into a generator, you just need to change print (b) to yield B. + deffib (max): -N,a,b = 0,0,1 + whileN <Max: A #print (b) at yieldb -A, B = b,a+b -n + = 1 - return ' Done'#message stored on exception - -G=FIB (10) in Print(g.__next__()) - #The main effect of this yield is that the function can be interrupted, and save the interrupt state, after the interruption, the code can continue to execute, over a period of time when the need to re-call this function, from the last yield of the next sentence to start execution. to + #The generator saves the algorithm, each time it calls next (g), calculates the value of the next element of G, until the last element is computed, and when there are no more elements, the stopiteration error (Exception) is thrown. - the #Exception Handling *g = FIB (6) $ whileTrue:Panax Notoginseng Try: -x =Next (g) the Print('g:', X) + A exceptstopiteration as E: the Print('Generator return value:', E.value) + Break - $ #implementing concurrent parallel operations with generators $ Import Time - defConsumer (name): - Print("%s ready to eat buns!"%name) the whileTrue: -Baozi =yieldWuyi the Print("Bun [%s] came, eaten by [%s]!"%(baozi,name)) - Wu - defproducer (name): Aboutc = Consumer ('A') $C2 = Consumer ('B') -C.__next__() -C2.__next__() - Print("Lao Tzu began to prepare steamed buns!") A forIinchRange (10): +Time.sleep (1) the Print("made 2 buns!") - c.send (i) $C2.send (i)#Pass the value of I to yield and to the next yield the theProducer"Dragon")
3. iterators
We already know that for
there are several types of data that can be directly acting on a loop:
A class is a collection of data types, such as,,, list
tuple
, and dict
set
str
so on;
One is generator
to include the generator and yield
the generator function with the band.
These objects, which can be directly applied to for
the loop, are called iterative objects: Iterable
.
You can use to isinstance()
determine whether an object is an Iterable
object:
from Import iterable>>> isinstance ([], iterable) True>>> isinstance ({}, iterable) True >>> isinstance ('abc', iterable) True for in Range (), iterable) True>>> isinstance (iterable) False
* An object that can be called by next()
a function and continually returns the next value is Iterator
called an iterator:.
In General: A generator is an iterator , and an iterator is not necessarily a generator (you don't have to look at it, you don't understand it)
Generators are Iterator
objects, but,, list
dict
str
Though Iterable
they are, they are not Iterator
.
Turn list
, dict
and str
wait for the Iterable
Iterator
function to be used iter()
:
1 >>> isinstance (ITER ([]), Iterator)2True3 > >> Isinstance (ITER ('abc'), Iterator)4 True
You may ask, why, list
dict
, str
etc. data types are not Iterator
?
This is because the Python Iterator
object represents a data stream, and the iterator object can be next()
called by the function and will return the next data continuously until there is no data to throw an StopIteration
error. You can think of this data stream as an ordered sequence, but we can't know the length of the sequence in advance, only by continuously using the next()
function to calculate the next data on demand, so Iterator
the calculation is lazy, and it will only be calculated when the next data needs to be returned.
Iterator
It can even represent an infinitely large stream of data, such as the whole natural number. Using list is never possible to store all natural numbers.
Python Basics (7)--iterators & Generators