1, iterators are a way to access the elements of a Collection. The iterator object is accessed from the first element of the collection until all of the elements have been accessed and Finished. Iterators can only move forward without going backwards, but That's fine, because people seldom retreat in the middle of an iteration. In addition, one of the great advantages of iterators is that they do not require that all elements in the entire iteration be prepared in Advance. An iterator computes an element only when it iterates over it, and before or after that, the element may not exist or be destroyed. This feature makes it ideal for traversing large or infinite collections, such as several G files
Characteristics:
- The visitor does not need to care about the structure inside the iterator, but simply continues to fetch the next content through the next () method
- A value in the collection cannot be accessed randomly, and can only be accessed from beginning to end
- You can't go back halfway through the INTERVIEW.
- Facilitates recycling of large data sets, saving memory
1 #creation of iterators2 #A=iter ([1,23,4,5,6,7,8,9])3 #print ("output this iterator:", a)4 #Print (a.__next__ ())5 #Print (a.__next__ ())6 #Print (a.__next__ ())7 #Print (a.__next__ ())8 #Print (a.__next__ ())9 #Print (a.__next__ ())Ten #Print (a.__next__ ()) one #Print (a.__next__ ()) a #Print (a.__next__ ())
2. 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;
1 defNrange (num):2Temp=-1;3 whileTrue:4Temp+=1;5 iftemp>=num:6 return7 Else:8 yieldTemp9Xr=nrange (9)Ten Print(xr.__next__()) one Print(xr.__next__()) a Print(xr.__next__())
3, the use of generators to implement single-threaded asynchronous concurrency, that is, the production of consumer models, the model can be analogous to the bank and other providers and recipients of the relationship between the model of service providers
1 #Producer Consumer Async2 Import time3 defConsumer (name):4 Print("%s ready to eat buns! "%Name)5 whileTrue:6Baozi=yield7 #A and B accept buns and start eating buns8 Print("bun "%s" came, eaten by "%s ""%(baozi,name))9 Ten defproducer (name): one #consumers A and B to the restaurant, ready to eat buns aC=consumer ("A"); -C1=consumer ("B"); -C.__next__(); thec1.__next__(); - #the boss receives information and prepares to make buns - Print("the boss is ready to make buns! ") - forIinchRange (10): +Time.sleep (1) - Print("made 2 buns! ") + #Buns done, sent to A and B a c.send (i) at c1.send (i) - -Producer"Eric")
iterators, generators, and asynchronous concurrency using generators to implement single threads