Iterators
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
To generate an iterator:
>>> a = [1,23,4,5,6,7,89,6,4,3,]>>> B =ITER (a)>>> B.__next__()1>>> B.__next__()23>>> B.__next__()4>>> B.__next__()5>>> B.__next__()6>>> B.__next__()7>>> B.__next__()89>>> B.__next__()6>>> B.__next__()4>>> B.__next__()3
Generator generator
Definition: 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
Code:
defcash_out (amount): whileAmount >0:amount-= 1yield1<br>Print("wipe, again to collect money ... Black sheep! ") ATM= Cash_out (5) Print("take money to%s million"% ATM.__next__())Print("take the flowers out!")Print("take money to%s million"% ATM.__next__())Print("take money to%s million"% ATM.__next__())Print("take the flowers out!")Print("take money to%s million"% ATM.__next__())Print("take money to%s million"% ATM.__next__())Print("take money to%s million"% ATM.__next__())#Then the money will be taken out, and then take the errorPrint("take money to%s million"% ATM.__next__())
Role:
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, after a period of time can also recall the function, from the last yield of the next sentence to start execution.
In addition, it can realize the effect of concurrency operation in single-threaded case by yield.
Import TimedefConsumer (name):Print("%s ready to eat buns!"%name) whileTrue:baozi=yield Print("Bun [%s] came, eaten by [%s]!"%(baozi,name))defproducer (name): C= Consumer ('A') C2= Consumer ('B') c.__next__() c2.__next__() Print("Lao Tzu began to prepare steamed buns!") forIinchRange (10): Time.sleep (1) Print("made 2 buns!") c.send (i) c2.send (i) Producer ("Alex")
Python Route (eight)-iterators & Generators