Basics python --- iterator

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

Iterator can remember the object is a traverse position. 

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

Iterator has two basic methods: iter () and next (). 

: Strings, a list of tuples or objects can be used to create iterators

 List = [1,2,3,4 ]
 IT = ITER (List)     # Create iterator object 
 Print (Next (IT))    # when the output of the iterator an element 
>>>. 1 Print (Next (IT))
 >>> 2 
iterator object may be used for a conventional traversing statement: 
List = [1,2,3,4 ] 
IT = ITER (List)     # Create iterator object for X in IT:
     Print (X, End = " " ) 
performing the above procedure, the output results are as follows: 1 2 3 4
 






May also be used next () function: Import sys # incorporated sys module List = [1,2,3,4 ] IT = ITER (List) # Create iterator object the while True: the try : Print (Next (IT)) the except the StopIteration : the sys.exit () performing the above procedure, the output results are as follows: . 1 2 . 3 . 4

 

Guess you like

Origin www.cnblogs.com/qjhh/p/12588423.html