Iterator pattern , Provide an external interface , Achieve sequential access to aggregated data , But the internal mechanism of this data is not shown .
Python The iterator pattern is well supported by itself , A few lines of code can be implemented .
stay Python in :
generator : For a data set , The generator does not remember every element value , But record the element position in the loop and calculate the value according to the element generation rules , This form of side loop and side calculation is generator .
iterator : Is a way to access collections , Remember the traversal position , Access... From the first element , Until the last element , And can only move forward, not backward . All can pass through next() The objects accessed are all iterator types , That is to say, a generator is a kind of iterator ;
Iteratable object : image List、Set、Str This can be done through for The type of loop traversal is an iteratable object , This traversal order can be from end to end . Iteratable objects can pass through iter() Convert to iterator .