Iterators
Iterators are a way to access the elements of a collection. The iterator is accessed from the first element of the collection until all the elements have been accessed and finished.
Features of iterators:
1. The visitor does not need to care about the internal structure of the iterator, only needs to go through the __next__ method to fetch the next content
2. You cannot directly access a value in the middle of the collection, only from the beginning to the end
3. Cannot be returned halfway through the visit
4. Suitable for access to large data combination, save memory
Li = iter (['AA','BB','cc'])#generate an iteratorPrint(Type (LI))#<class ' list_iterator ' >Print(Li.__next__())#Get Next value#AAPrint(Li.__next__())#BBPrint(Li.__next__())#cc
Generator
When a function call returns an iterator, the function is called the Generator (generator), and if the function contains the yield syntax, the function becomes the generator.
Yield: Breaks the function, saves the interrupt state, resumes execution of other code after the break, and executes the function again, starting with the next sentence of the last yield syntax
EF Money (Qian): whileQian >0:qian-= 100yield100Print('again to collect money, the Black sheep!!! ') ATM= Money (500)Print(ATM.__next__())Print(ATM.__next__())Print('a big health care.')Print(ATM.__next__())Print(ATM.__next__())Print(ATM.__next__())#Output Results100again to collect money, the Black sheep!!! 100come to a big health care again to withdraw money, the Black sheep!!! 100again to collect money, the Black sheep!!! 100again to collect money, the Black sheep!!! 100
Yield Async
Implementing concurrency in single-threaded scenarios
1 Import Time2 defConsumer (name):3 Print('%s ready to eat buns.'%name)4 whileTrue:5Baozi =yield6 Print('Bun [%s] came, eaten by [%s]'%(baozi,name))7 8 defShengchan (name):9c = Consumer ("A")TenC2 = Consumer ("B") OneC.__next__() AC2.__next__() - Print('%s started making buns.'%name) - forIinchRange (10): theTime.sleep (1)#after a second. - Print('%s made two buns'%name) - c.send (i) - c2.send (i) + -Shengchan ('Yoyo')
Iterators and generators