Note python basis of iterators and generators

Iterator:

     Python iteration is one of the most powerful features, is a way to access the collection elements.

     Iterator object began a visit from the first element of the collection until all elements are the visit. Iterator can only move forward , not backward.

     Iterator has two basic methods: ITER () and next ()

     Strings, lists, tuples or objects can be used to create an iterator

     

 

        Iterator object can be used for traversing statement:

        

 

        Results

 

        If you've already done once before the next traversal, then the result after traversing only 2,3,4,5,6,7,8

         

 

 

 Creating an iterator:

        The use as a class needs to implement an iterator two methods in a class the __iter __ () and the __next __ ()

        

 

Builder:

     In python, using the yield function generator is called.

       Generator is a function of the iterator returns each time it encounters yield when the function will pause and keep all of the current run, the return value of yield,

       Continue to operate from its current position and the next execution of the next () method.

       Calling a generator function, it returns an iterator object.

       

 

        The implementation of the above program, the output is:

 

        Note: a, b = b, a + b, such as the Yu a = b b = a + b

  

 

Guess you like

Origin www.cnblogs.com/7dao/p/12522272.html